<template>
  <!--自定义的tag标签-->
  <div>
    <div class="myInput" @click="onClick">
      <el-input
        :value="childValueUp"
        clearable
        readonly
        placeholder="请选择(可多选)"
      >
        <template v-slot:suffix>
          <i class="el-icon-circle-close" @click.stop="onClear"></i>
        </template>
      </el-input>
    </div>
    <!-- 新增 -->
    <el-dialog
      :visible.sync="dealShow"
      width="1440px"
      append-to-body
      :title="dealTitle"
    >
      <div class="dialog_main">
        <div class="treeBox">
          <vue-scroll v-if="treeList.length > 0">
            <el-tree
              :data="treeList"
              @node-click="handleNodeClick"
              :props="defaultProps"
              default-expand-all
              node-key="id"
              ref="tree"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span
                  style="
                    width: 160px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    display: inline-block;
                  "
                  :title="node.label"
                  >{{ node.label }}</span
                >
              </span>
            </el-tree>
          </vue-scroll>
          <div class="placeholderBox" v-else>
            <img src="@/assets/images/noData2.png" alt="" srcset="" />
            <p>{{ $t("message.videoManage.empty") }}</p>
          </div>
        </div>
        <div class="table_main">
          <el-form
            ref="dealForm"
            :model="dealForm"
            size="medium"
            class="dealForm"
            :inline="true"
          >
            <el-form-item label="姓名" prop="realName">
              <el-input
                v-model="dealForm.realName"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
              <!-- <el-input
                v-model="dealForm.roleName"
                placeholder="请输入"
              ></el-input> -->
              <el-select
                v-model="dealForm.roleId"
                filterable
                clearable
                :placeholder="$t('message.personnelAccess.juese')"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班组/部门" prop="departmentTeamId">
              <!-- <el-input
                v-model="dealForm.departmentTeamName"
                placeholder="请输入"
              ></el-input> -->
              <el-select
                v-model="dealForm.departmentTeamId"
                filterable
                placeholder="请选择班组/部门"
                clearable
              >
                <el-option
                  v-for="item in teamInfoList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="handleQuery"
                >查询</el-button
              >
              <el-button type="warning" plain @click="handleRefresh"
                >刷新</el-button
              >
            </el-form-item>
          </el-form>
          <!-- <div class="check_box">
            <div>
              已选{{
                $refs.selectedPersonnelAccountTable
                  ? $refs.selectedPersonnelAccountTable.selection.length
                  : 0
              }}项
            </div>
            <el-button @click="toggleSelection(false)" type="text" style="color: #f76c6c"
              >取消</el-button
            >
            <el-button @click="toggleSelection(true)" type="text">全选</el-button>
          </div> -->
          <el-table
            ref="selectedPersonnelAccountTable"
            :data="tableData"
            :row-key="propUserType.id"
            :height="440"
            class="tables"
            @select="handleSelectChange"
            @select-all="handleSelectChangeAll"
          >
            <el-table-column
              type="selection"
              align="center"
              width="55"
            ></el-table-column>
            <el-table-column prop="enterpriseName" label="所属企业">
            </el-table-column>
            <el-table-column align="center" prop="realName" label="姓名">
              <template slot-scope="scope">
                {{ scope.row.realName ? scope.row.realName : "--" }}({{
                  scope.row.account
                }})
              </template>
            </el-table-column>
            <el-table-column align="center" prop="roleName" label="角色">
            </el-table-column>
            <el-table-column
              align="center"
              prop="enterpriseName"
              label="所属班组/部门"
            >
              <template slot-scope="scope">
                {{ scope.row.departmentTeamName }}
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="dealForm.total > 0"
            :total="Number(dealForm.total)"
            :page.sync="dealForm.pageNo"
            :limit.sync="dealForm.pageSize"
            @pagination="getUpdatePersonListFn"
            :pageSizes="[...$store.state.PAGESIZRS, 100, 200, 500, 1000]"
            layout="total,sizes, prev, pager, next, jumper"
          />
        </div>
        <div class="selected_point">
          <div>
            <div>已选人员</div>
            <div @click="onRiskEmpty">清空</div>
          </div>
          <div class="selected_point_scroll">
            <el-tag
              v-for="tag in selectedList"
              :key="tag.id"
              :type="tag.userId === selectedInfo.userId ? '' : 'info'"
              @close="onRiskDelete(tag)"
              @click="onRiskClick(tag)"
              closable
            >
              {{ tag.realName ? tag.realName : "--" }}({{ tag.account }})
            </el-tag>
          </div>
        </div>
      </div>
      <div slot="footer" style="text-align: center">
        <el-button
          icon="el-icon-circle-close"
          size="medium"
          @click="dealFormCancel"
          >取消</el-button
        >
        <el-button
          icon="el-icon-circle-check"
          size="medium"
          type="primary"
          @click="submitDealForm"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getWorkerInfoList,
  selectHierarchyEnterpriseListApi,
} from "@/assets/js/api/laborPerson.js";
import {
  getProjectChilderSystemUserPageListApi,
  getProjectChilderSystemUserListApi,
  getBaseRoleListApi,
} from "@/assets/js/api/configManage.js";
import { getDepartmentAndTeamListApi } from "@/assets/js/api/operationManagement";
export default {
  name: "selectedPersonnelAccount",
  props: {
    value: {
      type: [Array, String, Number],
      default: () => [], //类型
    },
    enterpriseIds: {
      type: Array,
      default: () => [],
    }, // 企业id数组，用于过滤人员列表,
    enterpriseFlag: {
      type: Boolean,
      default: true,
    }, // 是否显示企业选择器
  },
  data() {
    return {
      childValue: [],
      treeList: [],
      // 对应的字段
      defaultProps: {
        children: "children",
        label: "enterpriseName",
      },
      dealShow: false,
      dealForm: {
        realName: "",
        roleName: "",
        roleId: "",
        departmentTeamName: "",
        departmentTeamId: "",
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      dealTitle: "人员选择器",
      tableData: [],
      treeListDetail: {},
      selectedList: [],
      selectedListValue: [],
      propUserType: {
        id: "userId",
      },
      selectedInfo: {},
      teamInfoList: [],
      roleList: [],
    };
  },
  watch: {
    "$props.value": {
      handler(val) {
        console.log(112233, val);
        this.childValue = val;
        this.selectedListValue = [];
        this.getProjectChilderSystemUserList();
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    childValueUp() {
      return this.selectedListValue instanceof Array &&
        this.selectedListValue.length > 0
        ? this.selectedListValue
            .map((item) => (item.realName ? item.realName : item.account))
            .join(",")
        : this.selectedListValue;
    },
  },
  methods: {
    handleNodeClick(data) {
      console.log(data);
      this.selectedInfo = {};
      this.treeListDetail = data;
      this.getTeamInfoList();
      this.handleQuery();
    },
    initDealForm() {
      this.dealForm = {
        realName: "",
        roleName: "",
        roleId: "",
        departmentTeamId: "",
        departmentTeamName: "",
        pageNo: 1,
        pageSize: 10,
        total: 0,
      };
    },
    submitDealForm() {
      this.selectedListValue = [...this.selectedList];
      this.childValue = this.selectedListValue.map(
        (item) => item[this.propUserType.id]
      );
      console.log(1122334455, this.childValue);
      this.$emit("input", this.childValue);
      this.dealShow = false;
    },
    onClear() {
      this.selectedListValue = [];
      this.childValue = this.selectedListValue.map(
        (item) => item[this.propUserType.id]
      );
      this.$emit("input", this.childValue);
    },
    dealFormCancel() {
      this.initDealForm();
      this.dealShow = false;
    },
    // 单选表单选择框
    handleSelectChange(selection, row) {
      console.log(selection, row);
      const findIndex = this.selectedList.findIndex(
        (item) => item[this.propUserType.id] === row[this.propUserType.id]
      );
      if (findIndex !== -1) {
        this.selectedList.splice(findIndex, 1);
      } else {
        this.selectedList.push(row);
      }
    },
    // 全选表单选择框
    handleSelectChangeAll(selection) {
      console.log(selection);
      this.tableData.forEach((ele) => {
        const findIndex = this.selectedList.findIndex(
          (item) => item[this.propUserType.id] === ele[this.propUserType.id]
        );
        if (selection.length > 0) {
          if (findIndex == -1) {
            this.selectedList.push(ele);
          }
        } else {
          if (findIndex !== -1) {
            this.selectedList.splice(findIndex, 1);
          }
        }
      });
    },
    onClick() {
      console.log("点击了");
      if (!this.enterpriseFlag && this.enterpriseIds.length == 0)
        return this.$message.warning("请选择企业后再进行操作！");
      this.getTreeList();
      this.initDealForm();
      this.dealTitle = "人员选择器";
      this.dealShow = true;
    },
    toggleSelection(flag) {
      if (flag) {
        // this.$refs.selectedPersonnelAccountTable.toggleAllSelection(true)
        this.toggleSelectionAll(this.tableData);
        // 全选
        this.handleSelectChangeAll(this.tableData);
      } else {
        this.$refs.selectedPersonnelAccountTable.clearSelection();
        // 取消全选
        this.handleSelectChangeAll([]);
      }
    },
    // 全选和取消全选
    toggleSelectionAll(dataList, isExpandAll = null) {
      console.log(112233, dataList, isExpandAll);
      dataList.forEach((item) => {
        if (isExpandAll == null) {
          this.$refs.selectedPersonnelAccountTable.toggleRowSelection(
            item,
            true
          );
        } else {
          this.$refs.selectedPersonnelAccountTable.toggleRowExpansion(
            item,
            isExpandAll
          );
        }
        if (item.children instanceof Array && item.children.length > 0) {
          this.toggleSelectionAll(item.children, isExpandAll);
        }
      });
    },
    onRiskClick(row) {
      if (row.userId == this.selectedInfo.userId) {
        this.selectedInfo = {};
        this.$refs.tree.setCurrentKey(this.treeList[0].id); // 默认选中节点第一个
        this.treeListDetail = this.treeList[0];
      } else {
        this.selectedInfo = row;
        const find = this.treeList.find((item) => item.id === row.enterpriseId);
        if (find) {
          this.$refs.tree.setCurrentKey(find.id); // 默认选中节点第一个
          this.treeListDetail = find;
        }
      }
      this.getUpdatePersonListFn();
    },
    onRiskDelete(row) {
      const findIndex = this.selectedList.findIndex(
        (item) => item[this.propUserType.id] === row[this.propUserType.id]
      );
      if (findIndex !== -1) {
        this.selectedList.splice(findIndex, 1);
      }
      const find = this.tableData.find(
        (item) => item[this.propUserType.id] === row[this.propUserType.id]
      );
      if (find) {
        this.$refs.selectedPersonnelAccountTable.toggleRowSelection(
          find,
          false
        );
      }
    },
    onRiskEmpty() {
      this.selectedList = [];
      this.$refs.selectedPersonnelAccountTable.clearSelection();
    },
    // 默认选中已选风险点 表格回显
    defaultToggleSelection() {
      this.tableData.forEach((ele) => {
        const findIndex = this.selectedList.findIndex(
          (item) => item[this.propUserType.id] === ele[this.propUserType.id]
        );
        if (findIndex !== -1) {
          this.$refs.selectedPersonnelAccountTable.toggleRowSelection(
            ele,
            true
          );
        }
      });
    },
    //获取所有角色
    getRoleList() {
      getBaseRoleListApi({
        projectSn: this.$store.state.projectSn,
      }).then((res) => {
        if (res.code == 200) {
          this.roleList = res.result;
        }
      });
    },
    getTeamInfoList() {
      let data = {
        projectSn: this.$store.state.projectSn,
        enterpriseIds: this.selectedInfo.enterpriseId
          ? this.selectedInfo.enterpriseId
          : this.treeListDetail.id,
      };
      // getTeamInfoListApi(data).then((res)=>{
        getDepartmentAndTeamListApi(data).then((res) => {
        if (res.code == 200) {
          this.teamInfoList = res.result;
        }
      });
    },
    // 分页获取人员列表信息
    getUpdatePersonListFn() {
      const departmentTeamId = this.dealForm.departmentTeamId ? [this.dealForm.departmentTeamId] : "";
      let data = {
        projectSn: this.$store.state.projectSn,
        // enterpriseId: this.treeListDetail.id,
        userId: this.selectedInfo.userId,
        enterpriseIds: this.selectedInfo.enterpriseId
          ? this.selectedInfo.enterpriseId
          : this.treeListDetail.id,
        pageNo: this.dealForm.pageNo,
        pageSize: this.dealForm.pageSize,
        realName: this.dealForm.realName,
        roleName: this.dealForm.roleName,
        departmentTeamName: this.dealForm.departmentTeamName,
        roleId: this.dealForm.roleId,
        teamIdList: departmentTeamId,
        departmentIdList: departmentTeamId,
      };
      getProjectChilderSystemUserPageListApi(data).then((res) => {
        console.log(res, this.childValue);
        if (res.code == 200) {
          this.tableData = res.result.records;
          this.dealForm.total = res.result.total;
          this.$nextTick(() => {
            if (this.childValue.length > 0) {
              // 默认选中已选风险点
              this.defaultToggleSelection();
              console.log(this.selectedList);
            }
          });
        }
      });
    },
    // 查询
    handleQuery() {
      this.dealForm.pageNo = 1;
      this.getUpdatePersonListFn();
    },
    // 刷新
    handleRefresh() {
      this.dealForm.pageNo = 1;
      this.dealForm.realName = "";
      this.dealForm.roleName = "";
      this.dealForm.departmentTeamName = "";
      this.dealForm.roleId = "";
      this.dealForm.departmentTeamId = "";
      this.getUpdatePersonListFn();
    },
    // 获取树状企业
    getTreeList() {
      this.treeList = [];
      selectHierarchyEnterpriseListApi({
        projectSn: this.$store.state.projectSn,
        enterpriseIds:
          this.enterpriseIds.length > 0 ? this.enterpriseIds.join(",") : "",
      }).then((result) => {
        if (result.success) {
          this.treeList = [
            {
              id:
                this.enterpriseIds.length > 0
                  ? this.enterpriseIds.join(",")
                  : "",
              enterpriseName: "全部",
              regionCode: "",
              regionName: "",
            },
            ...result.result,
          ];

          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.treeList[0].id); // 默认选中节点第一个
            this.treeListDetail = this.treeList[0];
            this.getTeamInfoList();
            this.getRoleList();
            this.getUpdatePersonListFn();
          });
        }
      });
    },
    // 获取已选人员列表
    getProjectChilderSystemUserList() {
      const userIds =
        this.childValue instanceof Array
          ? this.childValue.join(",")
          : this.childValue;
      if (!userIds) return (this.selectedList = []);
      let data = {
        projectSn: this.$store.state.projectSn,
        userIds: userIds,
      };
      getProjectChilderSystemUserListApi(data).then((res) => {
        if (res.code == 200) {
          this.selectedList = res.result;
          this.selectedListValue = res.result;
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-icon-circle-close {
  display: none;
}

.myInput:hover {
  .el-icon-circle-close {
    display: inline-block;
    cursor: pointer;
  }
}
.el-form-item {
  margin-bottom: 0;
}
.dialog_main {
  display: flex;
  height: 540px;
  .treeBox {
    width: 220px;
    height: calc(100%);
    background-color: rgba(216, 216, 216, 0.2);
    padding-top: 10px;
    position: relative;
    .treeStyle();
  }
  .table_main {
    padding: 0 16px;
    flex: 1;
    .el-input,
    .el-select {
      // width: 180px;
      width: 162px;
    }
    .tables {
      min-height: initial;
      width: 100%;
      // margin-top: 20px;
    }
    .check_box {
      display: flex;
      font-size: 14px;
      > .el-button {
        padding: 0;
        margin-left: 10px;
      }
      > .el-button:first-child {
        color: #eb4047;
      }
    }
    /deep/ .pagination-container {
      padding: 20px 16px;
    }
  }
  .selected_point {
    width: 268px;
    > div:first-child {
      display: flex;
      justify-content: space-between;
      > div:last-child {
        color: #2f6bef;
        cursor: pointer;
      }
    }
    .selected_point_scroll {
      height: calc(100% - 20px - 10px);
      border-radius: 0px 0px 0px 0px;
      margin-top: 10px;
      border: 2px solid #f3f5fc;
      padding: 6px 10px 10px 10px;
      overflow: auto;
      .el-tag {
        margin-left: 4px;
        margin-top: 4px;
        background-color: transparent;
      }
      .risk_point {
        width: 100%;
        margin-top: 6px;
        > div {
          justify-content: space-between;
          display: flex;
          align-items: center;
        }
      }
    }
  }
}
.treeStyle() {
  /deep/.el-tree {
    font-size: 15px;
    width: 100%;
    background-color: transparent;
    .el-tree-node {
      white-space: normal;
      &:focus > .el-tree-node__content {
        background-color: transparent;
      }
      &.is-current > .el-tree-node__content {
        background-color: rgba(81, 129, 246, 0.14);
        color: #5181f6;
      }
    }
    .el-tree-node__content {
      // height: 32px;
      padding: 7px 0;
      height: auto;
      line-height: 16px;
      position: relative;
      // margin-bottom: 7px;
      &:hover {
        background-color: rgba(81, 129, 246, 0.14);
        color: #5181f6;
      }

      .videoName {
        font-size: 14px;
      }
      .projectName {
        font-size: 14px;
        width: calc(100% - 55px);
        display: inline-block;
      }
      .companyName2 {
        font-size: 16px;
        font-weight: bold;
        display: inline-block;
        width: 192px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .el-tree-node__expand-icon {
      font-size: 16px;
      padding: 0 6px;
      &.is-leaf {
        color: transparent !important;
      }
    }
    .treeTitle {
      background-color: #f7f7f7;
      margin-bottom: 10px;
    }
  }
}
</style>
