<template>
  <div class="item-role-wrap">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond" :curmbThird="curmbThird"></bread-crumb>
    <div class="component-content screenSet" id="screenSet">
      <div class="header-title">
        查询条件
        <el-upload
          v-if="activeUser == 'L1'"
          class="upload-excel"
          action="#"
          accept=".xlsx"
          multiple
          :limit="1"
          :before-upload="beforeUpload"
        >
          <el-button size="small">导入角色权限</el-button>
          <el-button class="down-button" slot="tip" size="small" @click="download('model')">下载导入模板</el-button>
        </el-upload>
      </div>
      <el-row :gutter="30" class="row" type="flex" style="margin-top: 10px;">
        <el-form :model="formInline" ref="formInline" label-width="75px" class="form-inline">
          <el-col :span="6">
            <el-form-item label="所属机构：">
              <!-- <el-select size="small" v-model="formInline.organizationName" placeholder="请选择所属机构">
                <el-option
                  v-for="(item, index) in organizationList"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option
              </el-select>-->
              <el-input size="small" v-model="formInline.organizationName" placeholder="请输入机构名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="姓名：">
              <el-input size="small" v-model="formInline.userName" placeholder="请输入人员名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="角色：">
              <el-select size="small" v-model="formInline.projeceRole" placeholder="请选择角色">
                <el-option
                  v-for="(item, index) in roleList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- <el-col :span="5">
            <el-form-item label="所属科室：">
              <el-select size="small" v-model="formInline.departmentsName" placeholder="请选择所属科室">
                <el-option
                  v-for="(item, index) in departmentsList"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="6" style="padding:0;text-align:right;padding-right:10px;">
            <el-button type="primary" size="small" @click="searchList()">查询</el-button>
            <el-button
              type="default"
              size="small"
              @click="resetForm('formInline')"
              style="margin-left:0;"
            >重置</el-button>
          </el-col>
        </el-form>
      </el-row>
      <el-table :data="tableData" style="width: 100%">
        <!-- <el-table-column prop="userId" label="用户ID" align="center"></el-table-column> -->
        <el-table-column prop="userName" label="姓名" align="center"></el-table-column>
        <el-table-column prop="countyName" label="所属区县" align="center"></el-table-column>
        <el-table-column prop="organizationName" label="所属机构" align="center"></el-table-column>
        <el-table-column prop="departmentsName" label="科室" align="center"></el-table-column>
        <el-table-column prop="projeceRole" label="角色" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.projeceRole | projeceRoleType }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="area" label="负责区域" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.projeceRole == 'L2'">全部地区</span>
            <span v-if="scope.row.projeceRole == 'L0'">-</span>
            <span v-if="scope.row.projeceRole == 'L3' && scope.row.regions.length == 0">-</span>
            <span
              v-if="scope.row.projeceRole == 'L3' && scope.row.regions.length == 1"
            >{{ scope.row.regions[0] }}</span>
            <el-popover
              v-if="scope.row.projeceRole == 'L3' && scope.row.regions.length > 1"
              placement="bottom"
              title
              width="200"
              trigger="hover"
              class="more-text"
            >
              <p class="more-text">{{ scope.row.regions | areaList }}</p>
              <p slot="reference">{{ scope.row | areaText }}</p>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="350" align="left">
          <template slot-scope="scope">
            <el-button
              class="button-text"
              type="text"
              size="small"
              v-show="showButton(scope.row,'L2')"
              @click="openDialog(scope.row,'L2')"
            >升级项目负责人</el-button>
            <el-button
              class="button-text"
              type="text"
              size="small"
              v-show="showButton(scope.row,'L3')"
              @click="openDialog(scope.row,'L3')"
            >升级次级负责人</el-button>
            <el-button
              class="button-text"
              type="text"
              size="small"
              v-show="showButton(scope.row,'L3_2')"
              @click="openDialog(scope.row,'L3_2')"
            >降为次级负责人</el-button>
            <el-button
              class="button-text"
              type="text"
              size="small"
              v-show="showButton(scope.row,'L0')"
              @click="openDialog(scope.row,'L0')"
            >降为普通用户</el-button>
            <el-button
              class="button-text"
              type="text"
              size="small"
              v-show="showAppend(scope.row.projeceRole)"
              @click="addArea(scope.row)"
              :disabled="activeUser !== 'L1'"
            >追加区域权限</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <div class="table-empty">
            <img src="../../assets/image/no-content1.png" />
            <p>没有查询到相关结果</p>
          </div>
        </div>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="formInline.pageNo"
          :page-sizes="[10, 20, 30, 100]"
          :page-size="formInline.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows"
        ></el-pagination>
      </div>
      <el-dialog title :visible.sync="dialog.show" width="30%" center>
        <!-- <p v-if="numL3 > 1" class="dialog-p">
          确认将{{ dialog.role }}
          <span class="user-name">"{{ dialog.name }}"</span>
          {{ dialog.option }}吗?"
        </p>
        <p v-else >该用户为此机构仅有的次级负责人，确认需要降级吗？</p>-->

        <p
          v-if="numL3 <= 1 && scopeRow.projeceRole == 'L3'"
          class="dialog-p"
        >该用户为此机构仅有的次级负责人，确认需要降级吗？</p>
        <p v-else>
          确认将{{ dialog.role }}
          <span class="user-name">"{{ dialog.name }}"</span>
          {{ dialog.option }}吗?
        </p>

        <span slot="footer" class="dialog-footer">
          <el-button type="default" size="small" @click="dialog.show = false">取消</el-button>
          <el-button type="primary" size="small" @click="changeRole()">确定</el-button>
        </span>
      </el-dialog>
      <el-dialog title :visible.sync="dialogFull" width="30%" center>
        <p class="dialog-p">
          添加数量已达上限，不可继续添加
          <!-- <span class="user-name">5人</span> -->
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button type="default" size="small" @click="dialogFull = false">取消</el-button>
          <el-button type="primary" size="small" @click="dialogFull = false">确定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        title="导入成功"
        :visible.sync="dialogSuccess"
        width="30%"
        class="dialog-success"
        center
      >
        <p>
          本次成功导入
          <span class="upload-text">{{ updateNum }}条</span> 数据
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="small" @click="dialogSuccess = false">关闭</el-button>
        </span>
      </el-dialog>
      <el-dialog title="导入失败" :visible.sync="dialogFail" width="30%" class="dialog-fail" center>
        <div class="fail-type" v-if="failType == 1">
          <p>表格不符合格式要求，请修正后再次导入</p>
          <p class="fail-notice">仅支持一次导入5000条数据</p>
        </div>
        <div class="fail-type" v-if="failType == 2">
          <p>
            有
            <span class="fail-num">{{ failNum }}条</span> 数据不符合格式要求，请修正后再次导入
          </p>
          <p class="fail-notice">仅支持xlsx格式的文件</p>
          <p class="fail-link" @click="download('fail')">下载错误数据></p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="fail-close" size="small" @click="dialogFail = false">取消</el-button>
          <el-upload
            class="upload-button"
            action="#"
            accept=".xlsx"
            multiple
            :limit="1"
            :before-upload="beforeUpload"
          >
            <el-button
              stype="position: absolute;top: -14px;"
              type="primary"
              size="small"
              @click="updateAgain()"
            >重新导入</el-button>
          </el-upload>
        </span>
      </el-dialog>
      <el-dialog title="追加区域权限" :visible.sync="dialogArea" width="70%" class="dialog-area" center>
        <el-col class="area-choose" :span="15">
          <el-tree
            default-expand-all
            :data="treeData"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            @check="onChecked"
          >
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span>{{ node.label }}</span>
              <span>
                <el-button
                  type="text"
                  icon="el-icon-caret-bottom"
                  size="small"
                  @click="() => append(data,node)"
                ></el-button>
              </span>
            </span>
          </el-tree>
        </el-col>
        <el-col class="area-choose" :span="8">
          <p class="area-p">
            <i class="el-icon-bottom"></i>
            追加下列区域的学情报告查看权限 已选择({{ tagsRegion.length }})
          </p>
          <el-tag
            v-for="tag in tagsRegion"
            :key="tag.name"
            closable
            :type="tag.type"
            @close="handleCloseTree(tag)"
          >{{tag.name}}</el-tag>
        </el-col>
        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogArea = false">取消</el-button>
          <el-button type="primary" size="small" @click="updateAttachRegion()">确认</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import BreadCrumb from "../../components/breadcrumb.vue";
import { create } from "domain";
import { openLoading, closeLoading } from "../../utils/utils";
import * as commonUtil from "../../utils/utils";
import { getExeclUrl } from "@/utils/index";
import { uploadExcel } from "@/utils/education/educationApi";
import * as operationData from "../../utils/operation";
let vm = null;
export default {
  components: {
    BreadCrumb
  },
  data() {
    const item = {
      userId: "298490",
      userName: "李雪",
      projeceRole: "L0",
      organizationName: "浙江省人民医院",
      departmentsName: "外科"
    };
    return {
      curmbFirst: "系统管理",
      curmbSecond: "角色管理",
      curmbThird: "项目角色",
      tableData: [],
      loading: true,
      timingTime: "",
      totalRows: 0,
      currentPage: 1,
      formInline: {
        portalProjectId: "",
        pageNo: 1,
        pageSize: 10,
        departmentsName: "",
        organizationName: "",
        projeceRole: "",
        userName: ""
      },
      departmentsList: [],
      organizationList: [],
      roleList: [
        // {
        //   label: "内部管理员",
        //   value: "L1"
        // },
        {
          label: "全部",
          value: ""
        },
        {
          label: "项目负责人",
          value: "L2"
        },
        {
          label: "次级负责人",
          value: "L3"
        },
        {
          label: "普通用户",
          value: "L0"
        }
      ],
      numL2: 0,
      numL3: 0,
      dialog: {
        show: false,
        role: "项目负责人",
        name: "李雷",
        option: "升级为项目负责人",
        full: false
      },
      dialogFull: false,
      scopeRow: {},
      activeUser: "",
      updateNum: 0,
      dialogSuccess: false,
      failType: 2,
      failNum: 0,
      failExcelUrl: "",
      dialogFail: false,

      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf"
      },
      treeData: [],
      dialogArea: false,
      tagsRegion: [],
      doctorId: "",
      allSelectedKeys: [],
      attachRegionId: "",

      creator: false,
      hospitalMasterAdmin: false
    };
  },
  created() {
    vm = this;
    this.queryRoleList();
  },
  // 挂载到Dom完成时
  mounted: function() {
    commonUtil.resizeHeight();
  },
  methods: {
    updateAgain() {
      vm.dialogFail = false;
    },
    download(type) {
      let downloadUrl = "";
      if (type == "model") {
        downloadUrl = getExeclUrl(
          "%E6%95%99%E5%9F%B9%E9%A1%B9%E7%9B%AE%E8%A7%92%E8%89%B2%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
        );
      } else if (type == "fail") {
        downloadUrl = vm.failExcelUrl;
      }
      console.log("下载", type, downloadUrl);
      setTimeout(() => {
        window.open(downloadUrl);
      }, 500);
    },
    beforeUpload(file) {
      vm.dialogFail = false;

      console.log(file);
      let arr = file.type.split("/");
      let ext = "." + arr[1];
      let name = file.name;
      let reader = new FileReader();
      reader.onload = function(e) {
        let fileJson = {
          fileName: file.name,
          file: e.target.result.substr(e.target.result.indexOf("base64,") + 7),
          ext: ext
        };
        let fileArray = [
          {
            type: "",
            base64: fileJson
          }
        ];
        let req = {
          fileArray: fileArray
        };
        let projectId = vm.formInline.portalProjectId;
        console.log("req", req);
        let reqStr = JSON.stringify(req);
        console.log("reqStr", reqStr);
        openLoading(vm);
        uploadExcel(reqStr, projectId).then(res => {
          setTimeout(function() {
            closeLoading(vm);
            if (res.code == "000000") {
              if (res.data.success == true) {
                //导入成功
                vm.dialogSuccess = true;
                vm.updateNum = res.data.total;
                vm.queryRoleList();
              } else {
                if (res.data.outCount == true) {
                  //导入数据超5000
                  vm.failType = 1;
                  vm.dialogFail = true;
                  vm.failNum = res.data.total;
                  vm.failExcelUrl = res.data.url;
                } else {
                  //导入失败
                  // setTimeout(function() {
                  vm.failType = 2;
                  vm.dialogFail = true;
                  vm.failNum = res.data.total;
                  vm.failExcelUrl = res.data.url;
                  // }, 800);
                }
              }
            } else {
              //接口失败
              vm.$message.error(res.message);
            }
            console.log(res);
          }, 1000);
        });
      };
      reader.readAsDataURL(file);
    },
    searchList() {
      this.formInline.pageNo = 1;
      this.queryRoleList();
    },
    //查询用户列表
    queryRoleList() {
      this.formInline.portalProjectId = vm.getUrlSearch(
        window.location.href,
        "portalProjectId"
      );
      if (this.formInline.portalProjectId == null) {
        this.formInline.portalProjectId = "";
      }
      let req = {};
      req = this.formInline;
      openLoading(vm);
      vm.GET("portal/v2/role/queryRoleList", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          vm.tableData = res.data.projectRoleInfoModels;
          vm.totalRows = res.data.total;
          vm.activeUser = res.data.activeUser;
          vm.creator = res.data.creator;
          vm.hospitalMasterAdmin = res.data.hospitalMasterAdmin;
          //this.roleList = setRoleList(res.data.roleList);
          this.organizationList = res.data.organizationList;
          this.departmentsList = res.data.departmentsList;
          this.numL2 = res.data.numL2;
          this.numL3 = res.data.numL3;
        }
      });
    },
    //改变等级
    changeRole() {
      let req = {
        portalProjectId: this.formInline.portalProjectId,
        updateL: this.scopeRow.updateL,
        userId: this.scopeRow.userId,
        numL2: this.numL2,
        nowL: this.scopeRow.projeceRole
      };
      // vm.GET("portal/portalProjectOrRole/roleLevelUpdate", req).then(res => {
      vm.GET("portal/v2/role/roleLevelUpdate", req).then(res => {
        vm.dialog.show = false;
        if (res.code == "000000") {
          console.log(res);
          vm.queryRoleList();
          vm.$message({
            message: "设置成功！",
            type: "success"
          });
        } else {
          this.$message.error(res.code);
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.formInline.pageSize = val;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.formInline.pageNo = val;
      this.queryRoleList();
    },
    //重置表单
    resetForm() {
      vm.formInline = Object.assign(
        {},
        {
          portalProjectId: "",
          pageNo: 1,
          pageSize: 10,
          departmentsName: "",
          organizationName: "",
          projeceRole: "",
          userName: ""
        }
      );
      vm.queryRoleList();
    },
    //按钮展示情况
    showButton(row, projeceRole) {
      let flag = false;
      if (vm.activeUser == "L1") {
        //当前内部管理员
        if (row.projeceRole == "L2") {
          if (projeceRole == "L0" || projeceRole == "L3_2") {
            flag = true;
          }
        } else if (row.projeceRole == "L3") {
          if (projeceRole == "L2" || projeceRole == "L0") {
            flag = true;
          }
        } else if (row.projeceRole == "L0") {
          if (projeceRole == "L2" || projeceRole == "L3") {
            flag = true;
          }
        }
      } else if (vm.activeUser == "L2") {
        //当前项目负责人
        //新规则
        if (vm.creator == true) {
          //项目负责人是：项目创建者
          if (row.projeceRole == "L3") {
            if (projeceRole == "L2" || projeceRole == "L0") {
              flag = true;
            }
          } else if (row.projeceRole == "L0") {
            if (projeceRole == "L2" || projeceRole == "L3") {
              flag = true;
            }
          } else if (row.projeceRole == "L2") {
            //创建项目项目管理员可以修改其他项目管理员
            if (projeceRole == "L0" || projeceRole == "L3_2") {
              flag = true;
            }
          }
        } else {
          //不是项目创建者
          if (row.projeceRole == "L3") {
            if (projeceRole == "L0") {
              flag = true;
            }
          } else if (row.projeceRole == "L0") {
            if (projeceRole == "L3") {
              flag = true;
            }
          }
        }
      } else if (vm.activeUser == "L3") {
        //当前次级负责人
        //新规则
        if (vm.hospitalMasterAdmin == true) {
          //次级负责人是：构主管理员
          if (row.projeceRole == "L3") {
            if (projeceRole == "L0") {
              flag = true;
            }
          } else if (row.projeceRole == "L0") {
            if (projeceRole == "L3") {
              flag = true;
            }
          }
        }
      }
      return flag;
    },
    showAppend(projeceRole) {
      let flag = false;
      if (vm.activeUser == "L1" || vm.activeUser == "L1") {
        if (projeceRole == "L3") {
          flag = true;
        }
      }
      return flag;
    },
    //打开弹出框
    openDialog(row, projeceRole) {
      console.log(row);
      if (projeceRole == "L2" && this.numL2 >= 5) {
        this.dialogFull = true;
      } else {
        this.dialog.show = true;
      }
      this.dialog.name = row.userName;
      this.scopeRow = row;
      this.scopeRow.updateL = projeceRole;
      if (projeceRole == "L3_2") {
        this.scopeRow.updateL = "L3";
      }
      if (row.projeceRole == "L2") {
        this.dialog.role = "项目负责人";
        if (projeceRole == "L0") {
          this.dialog.option = "降级为普通用户";
        } else if (projeceRole == "L3_2") {
          this.dialog.option = "降级为次级负责人";
        }
      } else if (row.projeceRole == "L3") {
        this.dialog.role = "次级负责人";
        if (projeceRole == "L2") {
          this.dialog.option = "升级为项目负责人";
        } else if (projeceRole == "L0") {
          this.dialog.option = "降级为普通用户";
        }
      } else if (row.projeceRole == "L0") {
        this.dialog.role = "普通用户";
        if (projeceRole == "L2") {
          this.dialog.option = "升级为项目负责人";
        } else if (projeceRole == "L3") {
          this.dialog.option = "升级为次级负责人";
        }
      }
    },
    addArea(row) {
      vm.dialogArea = true;
      vm.treeData = [];
      vm.tagsRegion = [];
      vm.getAdministrative(row);
    },

    getAdministrative(row) {
      vm.doctorId = row.userId;
      // let req = {
      //   projectId: vm.formInline.portalProjectId
      // };
      let req = {
        projectId: vm.formInline.portalProjectId,
        doctorId: row.userId
      };
      openLoading(vm);
      // vm.GET("portal/portalProjectOrRole/getAttachRegion", req).then(res => {
      vm.GET("portal/v2/role/getAttachRegion", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          let administrativeAll = res.data.administrativeAll;
          let administrative = res.data.administrative;
          this.treeData = [];
          this.treeData[0] = administrativeAll;
          this.setTreeData(administrative);
          vm.attachRegionId = res.data.attachRegionId;
        }
      });
    },
    //初始化范围树
    setTreeData(administrative) {
      let treeIdList = [];
      let checkList = [];
      for (let i = 0; i < administrative.length; i++) {
        treeIdList.push(administrative[i].id);
        checkList[i] = {};
        checkList[i].name = administrative[i].label;
        checkList[i].key = administrative[i].id;
      }
      //console.log(treeIdList);
      this.$refs.tree.setCheckedKeys(treeIdList);
      this.tagsRegion = checkList;
    },
    initCheckList(allSelectedKeys) {
      this.tagsRegion = [];
      // console.log(allSelectedKeys);
      // console.log(this.$refs.tree.getCheckedNodes());
      let nodeData = this.$refs.tree.getCheckedNodes();
      for (let i = 0; i < nodeData.length; i++) {
        for (let j = 0; j < allSelectedKeys.length; j++) {
          if (
            allSelectedKeys[j].type == 1 &&
            nodeData[i].id == allSelectedKeys[j].key
          ) {
            let tagObj = {};
            tagObj.name = nodeData[i].label;
            tagObj.key = nodeData[i].id;
            this.tagsRegion.push(tagObj);
          }
        }
      }
    },
    onChecked() {
      // let cData = [],
      //   oldData = (this.treeData.length && this.treeData.slice()) || [],
      //   checkedKeys = this.$refs.tree.getCheckedKeys(),
      //   halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys(),
      //   savedCheckedKeys = this.handlerCheckedData(oldData, checkedKeys).map(
      //     key => {
      //       return { type: 1, key: key };
      //     }
      //   ),
      //   savedHalfCheckedKeys = halfCheckedKeys.map(key => {
      //     return { type: 2, key: key };
      //   }),
      //   allSelectedKeys = savedCheckedKeys.concat(savedHalfCheckedKeys);

      // vm.allSelectedKeys = allSelectedKeys;
      console.log(
        "getHalfCheckedKeys():",
        this.$refs.tree.getHalfCheckedKeys()
      );
      console.log(
        "getSimpleCheckedNodes():",
        operationData.getSimpleCheckedNodes(this.$refs.tree.store)
      );
      let checkedTree = operationData.getSimpleCheckedNodes(
        this.$refs.tree.store
      );
      let halfCheckedTree = this.$refs.tree.getHalfCheckedKeys();
      vm.allSelectedKeys = operationData.setSelectedKeys(
        checkedTree,
        halfCheckedTree
      );
      console.log("vm.allSelectedKeys", vm.allSelectedKeys);
      vm.initCheckList(vm.allSelectedKeys);
    },
    getTreeCheck() {
      // let cData = [],
      //   oldData = (this.treeData.length && this.treeData.slice()) || [],
      //   checkedKeys = this.$refs.tree.getCheckedKeys(),
      //   halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys(),
      //   savedCheckedKeys = this.handlerCheckedData(oldData, checkedKeys).map(
      //     key => {
      //       return { type: 1, key: key };
      //     }
      //   ),
      //   savedHalfCheckedKeys = halfCheckedKeys.map(key => {
      //     return { type: 2, key: key };
      //   }),
      //   allSelectedKeys = savedCheckedKeys.concat(savedHalfCheckedKeys);
      let checkedTree = operationData.getSimpleCheckedNodes(
        this.$refs.tree.store
      );
      let halfCheckedTree = this.$refs.tree.getHalfCheckedKeys();
      let allSelectedKeys = operationData.setSelectedKeys(
        checkedTree,
        halfCheckedTree
      );
      vm.allSelectedKeys = allSelectedKeys;
      return allSelectedKeys;
    },
    // // 递归删除列表中所有子节点
    // delSubKeysByNode(node, checkedKeys) {
    //   let idIndex;
    //   if (node.children && node.children.length) {
    //     if (node.children && node.children.length) {
    //       node.children.forEach(elm => {
    //         idIndex = checkedKeys.findIndex(id => {
    //           return id === elm.id;
    //         });
    //         if (idIndex > -1) {
    //           checkedKeys.splice(idIndex, 1);
    //         }
    //         if (elm.children && elm.children.length) {
    //           this.delSubKeysByNode(elm, checkedKeys);
    //         }
    //       });
    //     }
    //   }
    // },
    // // 去除子节点
    // handlerCheckedData(oldData, checkedKeys) {
    //   oldData.forEach(element => {
    //     for (let i = 0; i < checkedKeys.length; i++) {
    //       // 如果此节点被选中，则删除所有子节点
    //       if (element.id === checkedKeys[i]) {
    //         this.delSubKeysByNode(element, checkedKeys);
    //       } else {
    //         if (element.children && element.children.length) {
    //           this.handlerCheckedData(element.children, checkedKeys);
    //         }
    //       }
    //     }
    //   });
    //   return checkedKeys;
    // },
    //添加子节点
    append(data, node) {
      console.log("data:", data);
      console.log("node:", node);
      if (data.children.length == 0) {
        //let id = data.id + "add";
        let statusValue = 0;
        if (node.checked == true) {
          statusValue = 1;
        }
        let req = {
          id: data.id,
          status: statusValue,
          disabled: data.disabled
        };
        vm.GET("portal/scope/v1/administrative/children", req).then(res => {
          if (res.code == "000000") {
            let administrative = res.data.administrative;
            //console.log(administrative);
            data.children = administrative;
            this.appendCheck(administrative, node.checked);
          }
        });
      }
    },
    //子节点选中
    appendCheck(administrative, checked) {
      //console.log(checked,administrative)
      let checkList = [];
      checkList = this.$refs.tree.getCheckedKeys();
      if (checked) {
        for (let i = 0; i < administrative.length; i++) {
          checkList.push(administrative[i].id);
          // console.log(checkList);
        }
      }
      this.$nextTick(function() {
        this.$refs.tree.setCheckedKeys(checkList);
      });
    },
    //通过key设置tree
    setCheckedKeys(tagsRegion) {
      console.log(tagsRegion);
      let treeKeyList = [];
      for (let index = 0; index < tagsRegion.length; index++) {
        treeKeyList[index] = tagsRegion[index].key;
      }
      console.log(treeKeyList);
      this.$refs.tree.setCheckedKeys(treeKeyList);
    },

    //删除label节点 同步树结构
    handleCloseTree(tag) {
      this.tagsRegion.splice(this.tagsRegion.indexOf(tag), 1);
      this.setCheckedKeys(this.tagsRegion);
    },
    //设定的行政范围内容
    getScope(type) {
      let scope = "";
      let noChangeTree = this.getTreeCheck();
      console.log("this.allSelectedKeys", this.allSelectedKeys);
      if (this.allSelectedKeys.length > 0) {
        for (let i = 0; i < this.allSelectedKeys.length; i++) {
          scope +=
            this.allSelectedKeys[i].key + ":" + this.allSelectedKeys[i].type;
          if (i < this.allSelectedKeys.length - 1) {
            scope += "|";
          }
        }
      } else {
        // let noChangeTree = this.getTreeCheck();
        console.log("noChangeTree值", noChangeTree);
        if (noChangeTree.length > 0) {
          for (let i = 0; i < noChangeTree.length; i++) {
            scope += noChangeTree[i].key + ":" + noChangeTree[i].type;
            if (i < noChangeTree.length - 1) {
              scope += "|";
            }
          }
        } else {
          //选全国项目
          if (this.tagsRegion.length > 0 && this.tagsRegion[0].key == "000") {
            scope = "000:1";
            console.log(this.tagsRegion, "scope", scope);
          }
        }
      }

      //console.log(scope);
      return scope;
    },
    updateAttachRegion() {
      let req = {
        attachRegionId: vm.attachRegionId,
        doctorId: vm.doctorId,
        projectId: vm.formInline.portalProjectId,
        scopeOfAdministrative: vm.getScope()
      };
      console.log("req", req);
      vm.POST("portal/v2/role/insertOrUpdateAttachRegion", req).then(res => {
        if (res.code == "000000") {
          vm.$message({
            message: "设置成功",
            type: "success"
          });
          vm.dialogArea = false;
          vm.queryRoleList();
        } else {
          vm.$message.error(res.message);
        }
      });
    }
  }
};
</script>
<style lang="scss">
.item-role-wrap {
  .component-content {
    padding: 10px;
    background: #fff;
    .form-inline {
      margin-left: 30px;
    }
    .header-title {
      position: relative;
      padding: 10px 12px;
      font-size: 12px;
      color: #449284;
      border-bottom: 1px solid #efefef;
      .upload-excel {
        position: absolute;
        top: -2px;
        right: 27px;
        float: right;
      }
      .down-button {
        margin-left: 10px;
      }
    }
    .button-text {
      color: #449284;
    }
    .user-name {
      color: #449284;
    }
    .more-text {
      max-height: 40px;
      overflow-y: scroll;
    }
    .dialog-p {
      text-align: center;
      span {
        color: #449284;
      }
    }
    .dialog-success {
      p {
        text-align: center;
        .upload-text {
          color: #449284;
        }
      }
    }
    .dialog-fail {
      .fail-close {
        margin-left: -70px;
      }
      .upload-button {
        position: absolute;
        float: right;
        width: 80px;
        bottom: 20px;
        right: 120px;
      }
      .fail-type {
        p {
          margin-top: 10px;
        }
        .fail-num {
          color: #db3f52;
        }
        .fail-notice {
          color: #e3e3e3;
          font-size: 13px;
        }
        .fail-link {
          text-align: center;
          color: #449284;
          cursor: pointer;
        }
      }
    }
    .dialog-area {
      .el-tree-node__expand-icon {
        display: none;
      }
      .el-dialog {
        height: 700px;
        .el-dialog__body {
          overflow: hidden;
          .area-choose {
            padding: 10px 0 0 10px;
            height: 515px;
            overflow-y: scroll;
            border: 1px solid #dddddd;
            .el-icon-caret-bottom {
              color: #449284;
            }
            .area-p {
              color: #449284;
              margin-bottom: 10px;
            }
            .el-checkbox__input.is-indeterminate .el-checkbox__inner {
              background-color: #449284;
              border-color: #449284;
            }
            .is-checked .el-checkbox__inner {
              background-color: #449284;
              border-color: #449284;
            }
          }
        }
      }
      .el-tag {
        margin: 0 10px 10px 0;
        border: 1.3px solid #48a8fe;
        color: #1e92fe;
        background-color: #e7f6fe;
        .el-icon-close {
          width: 13px;
          height: 13px;
          line-height: 13px;
          font-size: 12px;
          background-color: #0486fe;
          border-radius: 50%;
          color: #d4edfe;
        }
      }
    }
    .table-empty {
      img {
        width: 100px;
      }
      p {
        margin-top: -50px;
      }
    }
  }
}
</style>