<!--编写穿梭框的插件，左右都有很多搜索条件-->
<template>
  <div>

    <div style="width: 98%;">
      <div class="tags-box" :class="{'tags-box-disabled':disabled,'tags-box-mini':size === 'mini'}" @click="showDialog">
        <el-tag type="success" :size="size" v-for="v in currentTempList" :key="v.id">{{ v.shortName }}</el-tag>

      </div>
      <div  class="tags_last" :class="{'tags-box-disabled':disabled}">
        <i v-if="currentTempList.length > 0 && !disabled" class="el-icon-circle-close close-icon" @click="clear"></i>
        <span v-show="currentTempList.length > 0" class="tags-num">{{ currentTempList.length }}</span>
      </div>
    </div>


    <DialogCom
      :title="title"
      :visible.sync="visible"
      width="80%"
      top="10vh"
      :close-on-click-modal="false"
      append-to-body
      @opened="open"
      @closed="closed"
    >
      <el-row class="el-row-top">
        <el-col :span="11">
          <el-card class="box-card leftbox" :body-style="{ height: '100%' }">
            <el-row class="result_row">
              <el-col :span="12">搜索条件</el-col>
            </el-row>
            <el-form
              ref="formleft"
              v-model="left.condition"
              label-width="120px"
              size="mini"
              style="width: 95%"
            >
            <el-row>
              <el-col :span="12">
                <el-form-item label="上级机构：">
                <tree-select
                  v-model="left.condition.orgId"
                  :searchable="searchable"
                  :default-expand-level="level"
                  :normalizer="tenantIdnormalizer"
                  :options="treeList"
                  :show-count="true"
                  :props="{ checkStrictly: true, label: 'name' }"
                  placeholder="请选择机构"
                  clearValueText="清除"
                  :noChildrenText="''"
                  @select="leftTreeSelect"
                  noOptionsText="没有数据"
                  noResultsText="没有搜索结果"
                />
              </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="机构类型：">
                <el-select
                  prop="type"
                  label="机构类型"
                  v-model="left.condition.orgType"
                  style="width: 100%"
                  placeholder="请选择机构类型"
                  @change="leftSearch"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.sys_org_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              </el-col>
            </el-row>
            
              <!--            <el-form-item >
                            <el-checkbox v-model="left.condition.searchChild" @change="leftSearch">是否包含下级</el-checkbox>
                          </el-form-item>-->
             <el-row>
               <el-col :span="12">
                <el-form-item label="机构名称：">
                <el-input
                  v-model="left.condition.orgName"
                  clearable
                  @input="leftSearch"
                ></el-input>
              </el-form-item>
              </el-col>
             </el-row>            
            </el-form>
            <el-row class="result_row">
              <el-col :span="12">搜索结果</el-col>
              <el-col :span="12" style="text-align: right"
              >{{ left.selectedRows.length }}/{{ left.data.length }}
              </el-col
              >
            </el-row>
            <el-table
              style="width: 99%;margin:auto;"
              height="calc(100% - 148px)"
              :data="left.data"
              @selection-change="handleLeftSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="affiliatedArea" align="center" label="地区"></el-table-column>
              <el-table-column prop="affiliatedBank" label="行社" align="center"></el-table-column>
              <el-table-column prop="shortName" label="机构名称" align="center"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
        <el-col :span="2">
          <div class="controller">
            <el-button type="primary" @click="handleAdd">添加 >></el-button>
            <el-button class="remove" type="primary" @click="handleRemove">移除 <<</el-button>
          </div>
        </el-col>
        <el-col :span="11">
          <el-card class="box-card" :body-style="{ height: '100%' }">
            <el-row class="result_row">
              <el-col :span="12">搜索条件</el-col>
            </el-row>
            <el-form
              ref="formRight"
              v-model="right.condition"
              label-width="120px"
              size="mini"
              style="width: 95%"
            >
            <el-row>
              <el-col :span="12">
                <el-form-item label="组织机构：">
                <tree-select
                  v-model="right.condition.orgId"
                  :searchable="searchable"
                  :options="treeList"
                  :default-expand-level="level"
                  :normalizer="tenantIdnormalizer"
                  :show-count="true"
                  :props="{ checkStrictly: true, label: 'name' }"
                  placeholder="请选择归属机构"
                  clearValueText="清除"
                  :noChildrenText="''"
                  @select="rightTreeSelect"
                  noOptionsText="没有数据"
                  noResultsText="没有搜索结果"
                />

              </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="机构类型：">
                <el-select
                  prop="type"
                  label="机构类型"
                  v-model="right.condition.orgType"
                  style="width: 100%"
                  placeholder="请选择机构类型"
                  @change="rightSearch"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.sys_org_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              </el-col>
            </el-row>
              
              <!--            <el-form-item >
                            <el-checkbox v-model="right.condition.searchChild" @change="rightSearch">是否包含下级</el-checkbox>
                          </el-form-item>-->
             <el-row>
               <el-col :span="12">
                <el-form-item label="机构名称：">
                <el-input
                  v-model="right.condition.orgName"
                  clearable
                  @input="rightSearch"
                ></el-input>
              </el-form-item>
              </el-col>
             </el-row>             
            </el-form>
            <el-row class="result_row">
              <el-col :span="12">搜索结果</el-col>
              <el-col :span="12" style="text-align: right"
              >{{ right.selectedRows.length }}/{{ right.data.length }}
              </el-col
              >
            </el-row>
            <el-table
              style="width: 99%;margin:auto;"
              height="calc(100% - 148px)"
              :data="right.data"
              @selection-change="handleRightSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="affiliatedArea" label="地区"></el-table-column>
              <el-table-column prop="affiliatedBank" label="行社"></el-table-column>
              <el-table-column prop="shortName" label="机构名称"></el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="onOK">确定</el-button>
    </span>
    </DialogCom>


  </div>
</template>
<script>
import {selectOrgList} from "@/api/system/org.js";

const defaultData = {
  left: {
    condition: {
      orgId: null,
      orgName: "",
      orgType: null,
      searchChild: false,
    },
    total: 0,
    selectedCount: 0,
    selectedRows: [],
    data: [],
  },
  right: {
    condition: {
      orgId: null,
      orgName: "",
      orgType: null,
      searchChild: false,
    },
    total: 0,
    selectedCount: 0,
    selectedRows: [],
    data: [],
  },
}
export default {
  name: "orgSelect",
  dicts: ["sys_org_type"],
  props: {
    orgList : {
      type: Array,
      default: new Array(),
    },
    size: {
      type: String,
      default: 'small',
    },
    trigger: {
      type: String,
      default: 'click',
    },
    //组件禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customRequest: {
      type: Function,
    },
    hangsheTree: {
      type: Boolean,
      default: false,
    },
    businessTree: {
      type: Boolean,
      default: false,
    },
    wholeTree: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    orgList: function (data) {
      this.currentTempList = this.orgList;
    }
  },
  data() {
    return {
      orgs: [],
      title: "选择机构",
      level: 1,
      clearable: true,
      searchable: true,
      visible: false,
      deviceType: null,
      loading: false,
      treeList: [],
      deptOptions: [],
      currentTempList: [],
      boundOrgsClone: [],
      left: {
        condition: {
          orgId: this.$store.getters.orgId,
          deviceName: "",
          searchChild: false,
        },
        total: 0,
        selectedCount: 0,
        selectedRows: [],
        data: [],
      },
      right: {
        condition: {
          orgId: this.$store.getters.orgId,
          deviceName: "",
          searchChild: false,
        },
        total: 0,
        selectedCount: 0,
        selectedRows: [],
        data: [],
      },
      rightOrgIds: [],
      boundOrgIds: [],
      searchOrgs: [],

    };
  },
  created() {
    this.boundOrgsClone = [];
  },
  mounted() {

  },

  methods: {
    clear() {
      this.currentTempList = [];
      this.boundOrgsClone = [];
      this.$emit("selectNode", []);
      this.$emit("selectNodeId", []);
    },

    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.shortName,
        children: node.children,
      };
    },
    orgTree() {

      //获取所有机构列表
      this.getAllOrgs();

      if (this.customRequest) {
        this.customRequest().then((response) => {
          this.treeList = response.data;
          return;
        });
      } else {
        if (this.hangsheTree) {
          this.treeList = this.$store.getters.depTree;
        } else if (this.businessTree) {
          this.treeList = this.$store.getters.businessTree;
        } else if (this.wholeTree) {
          this.treeList = this.$store.getters.wholeTree;
        } else {
          this.treeList = this.$store.getters.orgTree;
        }
      }
    },
    getChildIds(orgTree, parentId) {
      if (parentId) {
        orgTree.forEach((v, i) => {
          if (v.path.indexOf(parentId) != -1) {
            this.rightOrgIds.push(v.id);
          }

          if (v.children && v.children.length > 0) {
            this.getChildIds(v.children, parentId);
          }
        });
      }
    },
    open() {
      this.right.data = JSON.parse(JSON.stringify(this.currentTempList));
      this.boundOrgsClone = JSON.parse(JSON.stringify(this.currentTempList));
      //this.leftSearch();
    },
    showDialog() {
      this.orgTree();
      this.visible = true;
    },
    hideDialog() {
      this.visible = false;
      this.left = defaultData.left;
      this.right = defaultData.right;
      this.searchOrgs = [];
      this.boundOrgIds = [];
      this.boundOrgsClone = [];
    },
    closed() {
      this.left = defaultData.left;
      this.right = defaultData.right;
      this.searchOrgs = [];
      this.boundOrgIds = [];
      this.boundOrgsClone = [];
      this.left.data = [];
      this.right.data = [];
      this.left.condition.orgId = this.$store.getters.orgId;
      this.right.condition.orgId = this.$store.getters.orgId;
      this.left.condition.orgType = null;
      this.right.condition.orgType = null;
      this.left.condition.orgName = null;
      this.right.condition.orgName = null;
    },
    leftTreeSelect(node) {
      this.left.condition.orgId = node.id;
      this.left.condition.orgPath = node.path;
      this.leftSearch();
    },
    rightTreeSelect(node) {
      this.right.condition.orgId = node.id;
      this.right.condition.orgPath = node.path;
      this.rightSearch();
    },
    handleLeftSelectionChange(val) {
      this.left.selectedCount = val.length;
      this.left.selectedRows = val;
    },
    handleRightSelectionChange(val) {
      this.right.selectedCount = val.length;
      this.right.selectedRows = val;
    },
    handleAdd() {
      this.right.condition.orgId = null;
      this.right.condition.orgType = null;
      this.right.condition.orgName = null;
      let addData = this.left.selectedRows.filter(
        (row) => this.boundOrgIds.indexOf(row.id) < 0
      );
      if (addData.length > 0) {
        addData.forEach((i, v) => {
          this.right.data.push(i);
          this.boundOrgsClone.push(i);
        });
        this.boundOrgIds = this.boundOrgsClone.map((d) => d.deviceId);

        this.left.data = this.searchOrgs.filter((row) => this.boundOrgIds.indexOf(row.id) < 0)
      }
      this.leftSearch();
    },
    handleRemove() {
      /* this.right.condition.orgId = null;
       this.right.condition.orgType = null;
       this.right.condition.orgName = null;
       this.right.condition.orgPath = null;*/
      let rightSelectedIds = this.right.selectedRows.map(
        (r) => r.id
      );
      if (rightSelectedIds.length > 0) {
        this.right.data = this.right.data.filter(
          (d) => rightSelectedIds.indexOf(d.id) < 0
        );
        this.boundOrgsClone = this.boundOrgsClone.filter(
          (d) => rightSelectedIds.indexOf(d.id) < 0
        );
        this.boundOrgIds = this.boundOrgsClone.map((d) => d.id);

        this.left.data = this.searchOrgs.filter((row) => this.boundOrgIds.indexOf(row.id) < 0)
        if (this.left.condition.orgId) {
          this.leftSearch();
        }
      }


    },
    getAllOrgs() {      
      selectOrgList({orgId:this.$store.getters.orgId,checkSub:true}).then((result) => {
        this.orgs = result;
      });
    },
    leftSearch() {
      let {condition} = this.left;
      this.left.prevCondition = {...condition};
      this.boundOrgIds = this.boundOrgsClone.map((d) => d.id);
      this.left.data = this.orgs
        .filter(
          (d) => this.boundOrgIds.indexOf(d.id) < 0
        )
        .filter(
          (d) => !condition.orgName || d.shortName.includes(condition.orgName)
        )
        .filter(
          // 过滤机构类型
          (d) => !condition.orgType || d.type == condition.orgType
        )
        .filter(
          // 过滤父级机构
          (d) => !condition.orgPath || d.path.includes(condition.orgPath)
        );
    },
    rightSearch() {
      const {condition} = this.right;
      if (this.boundOrgsClone.length > 0) {
        this.right.data = this.boundOrgsClone
          .filter(
            // 过滤机构名称
            (d) =>
              !condition.orgName || d.shortName.includes(condition.orgName)
          )
          .filter(
            // 过滤机构类型
            (d) => !condition.orgType || d.type == condition.orgType
          )
          .filter(
            // 过滤父级机构
            (d) => !condition.orgPath || d.path.includes(condition.orgPath)
          );
      }
    },
    onOK() {
      this.currentTempList = this.boundOrgsClone;
      this.$emit("selectNodeId", this.boundOrgIds);
      this.hideDialog();
    },
  },
  model: {
    event: "selectNodeId",
  },
};
</script>

<style lang="scss" scoped>

.result_row {
  width: 96%;
  padding: 6px;
}

.dialog-footer {
  float: right;
  margin: 10px 0px;
}

::v-deep .el-dialog__footer {
  height: 60px;
}

::v-deep .el-dialog__body {
  padding: 10px 5px;
}

::v-deep .el-card__body {
  padding: 10px 5px;
}

.controller {
  margin: auto;
  width: 80px;
  top: calc(50% - 30px);
  position: relative;

  .remove {
    margin-top: 20px;
    margin-left: 0px;
  }
}

.el-row-top {
  height: 550px;
  display: flex;

  v-deep & > .el-col {
    height: 100%;
    width: calc(50% - 50px);
  }

  v-deep & > .el-col:nth-child(2) {
    width: 100px;
  }
}

.box-card {
  height: 100%;
  display: flex;
  justify-content: space-between;

  v-deep .el-card__body {
    height: 100%;
  }
}

.leftbox {
  v-deep .k-tree-select__clear {
    display: none !important;
  }
}

.deviceName-column-content {
  display: block;
  text-align: right;
}


.tags-box {
  background-color: #fff;
  border-radius: 4px;
  border-top: 1px solid #dcdfe6; /* 上边框 */
  border-bottom: 1px solid #dcdfe6; /* 下边框 */
  border-left: 1px solid #dcdfe6; /* 左边框 */
  border-right: none; /* 取消右边框 */
  color: #606266;
  outline: 0;
  padding: 0 40px 0 5px;
  width: 90%;
  min-height: 40px;
  max-height: 40px;
  position: relative;
  overflow: hidden;
  display: inline-block;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}
.tags_last{
  background-color: #fff;
  border-radius: 4px;
  border-top: 1px solid #dcdfe6; /* 上边框 */
  border-bottom: 1px solid #dcdfe6; /* 下边框 */
  border-right: 1px solid #dcdfe6; /* 左边框 */
  border-left: none; /* 取消右边框 */
  color: #606266;
  outline: 0;
  width: 10%;
  float: right;
  min-height: 40px;
  max-height: 40px;
  > span {
    margin: 5px 10px;
    color: #161617;
  }
  .close-icon {
    position: absolute;
    right: 28px;
    cursor: pointer;
    margin: 10px 10px;
    &:hover {
      color: #aaa;
    }
  }
}

.tags-box-disabled {
  background-color: #F5F7FA;
  border-color: #E4E7ED;
  color: #C0C4CC;
  cursor: not-allowed;
}

.tags-box-mini {
  min-height: 32px;
  max-height: 32px;
  line-height: 32px;

  > span {
    margin: 0 5px;
  }

  > .tags-num {
    line-height: 38px;
  }
}

.tags-num {
  color: #ccc;
  position: absolute;
  right: 48px;
  top: -4px;
}

.tree-box {
  margin-top: 20px;
  max-height: 300px;
  overflow: auto;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  user-select: none;
}
</style>
