<template>
  <div class="organization-alert">
    <div class="organization-left">
      <div>已选:{{ allSelect.length }}个人员</div>
      <div class="hcd">
        <div class="tag-list">
          <el-tag
            :key="item.id"
            v-for="item in allSelect"
            closable
            :disable-transitions="false"
            style="margintop: 10px"
            @close="handleClose(item)"
          >
            {{
              item.name.length > 12 ? item.name.slice(0, 12) + '...' : item.name
            }}
          </el-tag>
        </div>
      </div>

      <el-row justify="space-around" type="flex" class="btn-left">
        <el-button type="primary" size="small" @click="addFn"
          >确定添加</el-button
        >
        <el-button size="small" @click="canclefn">取消</el-button>
      </el-row>
    </div>
    <div class="organization-right">
      <el-form
        :inline="true"
        :model="formOrganization"
        class="demo-form-inline"
      >
        <el-form-item label>
          <el-input
            style="width: 140px"
            size="small"
            v-model:value="formOrganization.name"
            placeholder="请输入机构名称"
          ></el-input>
        </el-form-item>
        <el-form-item label>
          <el-input
            style="width: 140px"
            size="small"
            v-model:value="formOrganization.peopleName"
            placeholder="请输入人员名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="searchOrganization()"
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="resetOrgOrPerson()"
            >取消搜索</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        class="rim"
        ref="multipleOrganization"
        :data="tableOrganization"
        tooltip-effect="dark"
        @select-all="selectAllOrganization"
        @select="selectOrganization"
      >
        <el-table-column
          type="selection"
          :selectable="selectableTableList"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="人员名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="department"
          label="所属科室"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="hospital"
          label="所属医院"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="provinceName"
          label="所属省份"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="cityName"
          label="所属城市"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="countyName"
          label="所属区县"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="townName"
          label="所属街道"
          align="center"
        ></el-table-column>
        <template v-slot:empty>
          <div>
            <div class="table-empty">
              <img src="../../../assets/image/no-content1.png" />
              <p>没有机构信息</p>
            </div>
          </div>
        </template>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeOrganization"
          @current-change="handleCurrentOrganization"
          :current-page="formOrganization.pageNum"
          :page-sizes="[10, 30, 50, 100, 200]"
          :page-size="formOrganization.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalOrganization"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { $on, $off, $once, $emit } from '../../../../utils/gogocodeTransfer'
import { openLoading, closeLoading } from '@/utils/utils'
import { doUpload, getFilePath } from '@/utils/qiniu-util'
import * as operationData from '@/utils/operation'
import { getCircleProvincesReq } from '@/utils/yqrange/rangeApi'
import {
  moPeopleOption,
  moRelAddSearch,
  moPeopleSave,
  clearPeopleCacheOrg,
} from '@/utils/yqrange/memberApi'
let vm = null
export default {
  props: {
    circleId: {
      type: Number | String,
      default: 1,
    },
    roleType: {
      type: Number | String,
      default: 1,
    },
  },
  data() {
    return {
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node
          if (node.level == 1) {
            let req = {
              provinceId: node.data.value,
            }
            vm.GET('basic-data/position/cities', req).then((res) => {
              let newData = vm.setMoreOption(res.data.cityList, 'cities')
              resolve(newData)
            })
          } else if (node.level == 2) {
            let req = {
              cityId: node.data.value,
            }
            vm.GET('basic-data/position/counties', req).then((res) => {
              let newData = vm.setMoreOption(res.data.countyList, 'counties')
              resolve(newData)
            })
          } else if (node.level == 3) {
            let req = {
              countyId: node.data.value,
            }
            vm.GET('basic-data/position/towns', req).then((res) => {
              let newData = vm.setMoreOption(res.data.townList, 'towns')
              resolve(newData)
            })
          }
        },
      },
      administrativeValue: '',
      tableOrganization: new Array(),
      currentOrganization: 1,
      totalOrganization: 10,
      pageSizeOrganization: 2,
      selectionList: [],
      formOrganization: {
        name: '', //机构名称
        peopleName: '', //人员名称
        administrativeId: '',
        administrativeIdList: [],
        level: '',
        chechAll: true,
        pageNum: 1,
        pageSize: 10,
      },
      allSelect: [],
    }
  },
  created() {
    vm = this
  },
  async mounted() {
    this.clear()
    this.initRange()
    //Idtype:1,内部 2.外部
    vm.idType = localStorage.getItem('storageIdType')
  },
  methods: {
    clear() {
      clearPeopleCacheOrg(this.circleId)
        .then(() => {})
        .catch((err) => {
          console.log(err)
        })
    },
    // 多级地区
    setMoreOption(data, type) {
      let option = []
      for (let i = 0; i < data.length; i++) {
        let obj = data[i]
        if (type == 'cities') {
          obj.label = data[i].cityName
          obj.value = data[i].cityId
        } else if (type == 'counties') {
          obj.label = data[i].countyName
          obj.value = data[i].countyId
        } else if (type == 'towns') {
          obj.label = data[i].townName
          obj.value = data[i].townId
          obj.leaf = true
        }
        option.push(obj)
      }
      return option
    },
    initRange() {
      vm.getOrganization()
      this.formOrganization.pageNum = 1
      this.formOrganization.name = ''
      this.formOrganization.level = ''
    },
    //查询所有的人员列表
    getOrganization() {
      let req = {
        circleId: this.circleId,
        name: this.formOrganization.peopleName,
        orgName: this.formOrganization.name,
        pageNo: this.formOrganization.pageNum,
        pageSize: this.formOrganization.pageSize,
      }
      openLoading(vm)
      moRelAddSearch(req)
        .then((res) => {
          closeLoading(this)
          if (res.code == '000000') {
            this.tableOrganization = res.data.peoplesDtoList
            this.totalOrganization = res.data.total
            vm.initOrganizationStatus()
          } else {
            this.$message(res.message)
          }
        })
        .catch((err) => {
          this.$message.error('请求失败')
        })
    },
    // 获取机构列表的机构状态（是否被选中）
    initOrganizationStatus() {
      let tableStatus = this.tableOrganization
      tableStatus.forEach((row) => {
        if (row.status == 1 || row.status == 2) {
          this.$nextTick(function () {
            this.$refs.multipleOrganization.toggleRowSelection(row)
            this.selectionList.push(row)
          })
        }
      })
    },
    //选择搜索机构方式
    searchOrganization() {
      this.formOrganization.pageNum = 1
      let searchForm = this.formOrganization
      this.getOrganization()
    },
    //重置机构、人员查询
    resetOrgOrPerson() {
      vm.formOrganization.name = ''
      vm.formOrganization.peopleName = ''
      vm.formOrganization.pageNum = 1
      vm.searchOrganization()
    },
    // 更改每页显示的数据数量
    handleSizeOrganization(val) {
      console.log(`每页 ${val} 条`)
      this.formOrganization.pageSize = val
      this.searchOrganization()
    },
    // 更改当前页数
    handleCurrentOrganization(val) {
      //console.log(`当前页: ${val}`);
      this.formOrganization.pageNum = val
      this.getOrganization()
    },
    //人员table中勾选一页
    selectAllOrganization(selection) {
      this.selectionList = selection
      let setList = []
      let selectList = []
      for (let i = 0; i < vm.tableOrganization.length; i++) {
        if (vm.tableOrganization[i].status != 2) {
          setList.push(vm.tableOrganization[i].id)
        }
      }
      for (let j = 0; j < selection.length; j++) {
        selectList.push(selection[j].id)
      }
      let intersect = operationData.getIntersect(setList, selectList)
      let typeStatus = 0
      if (intersect.length > 0) {
        typeStatus = 1
      }
      // let  = this.$refs.multipleTable.selection
      console.log(selection, setList, selectList)
      if (setList.length > 0) {
        let req = {
          ids: setList,
          circleId: this.circleId,
          type: typeStatus,
        }
        openLoading(vm)
        moPeopleOption(req)
          .then((res) => {
            closeLoading(vm)
            if (res.code == '000000') {
              this.checkToList(req.type, vm.tableOrganization)
            } else {
              this.$message(res.message)
            }
          })
          .catch((err) => {
            this.$message.error('请求失败')
          })
      }
    },
    //机构人员中勾选一个
    selectOrganization(selection, row) {
      this.selectionList = selection
      let flag = false
      for (let i = 0; i < selection.length; i++) {
        if (selection[i].id == row.id) {
          flag = true
        }
      }
      let req = {
        ids: [row.id],
        circleId: this.circleId,
        type: flag === false ? 0 : 1,
      }
      openLoading(vm)
      moPeopleOption(req)
        .then((res) => {
          closeLoading(vm)
          if (res.code == '000000') {
            this.checkToList(req.type, row)
          } else {
            this.$message(res.message)
          }
        })
        .catch((err) => {
          this.$message.error('请求失败')
        })
    },
    selectableTableList(row, index) {
      // if (this.status4Flag == 1) {
      if (row.status == 2) {
        return false
      }
      return true
      // }
      // return true;
    },
    // 通过check改变展示的已选中的数据列表
    checkToList(type, item) {
      if (type) {
        if (Array.isArray(item)) {
          this.allSelect = this.unique([...this.allSelect, ...item])
        } else {
          this.allSelect.push(item)
        }
      } else {
        if (Array.isArray(item)) {
          for (var i = this.allSelect.length - 1; i >= 0; i--) {
            for (let j = item.length - 1; j >= 0; j--) {
              if (
                this.allSelect[i] &&
                item[j] &&
                this.allSelect[i].id == item[j].id
              ) {
                this.allSelect.splice(i, 1)
              }
            }
          }
        } else {
          for (let i = this.allSelect.length - 1; i >= 0; i--) {
            if (this.allSelect[i].id == item.id) {
              this.allSelect.splice(i, 1)
            }
          }
        }
      }
    },
    // 去重
    unique(arr) {
      let hashTable = {}
      let newArr = []
      for (let i = 0, l = arr.length; i < l; i++) {
        if (!hashTable[arr[i].id] && arr[i].status != 2) {
          hashTable[arr[i].id] = true
          newArr.push(arr[i])
        }
      }
      return newArr
    },
    //删除已选中的tag
    handleClose(item) {
      this.selectOrganization([], item)
      this.$refs.multipleOrganization.toggleRowSelection(item)
    },
    // 确定添加
    addFn() {
      if (!(this.allSelect && this.allSelect.length)) {
        this.$message.error('已选列表为空')
        return
      }
      let params = {
        circleId: this.circleId,
      }
      moPeopleSave(params)
        .then(() => {
          $emit(this, 'addPeople')
        })
        .catch(() => {
          this.$message.error('保存失败,请重试')
        })
    },
    // 取消
    canclefn() {
      $emit(this, 'handleClose')
    },
  },
  emits: ['addPeople', 'handleClose'],
}
</script>

<style lang="scss" scoped>
.organization-alert {
  display: flex;
  background: #fff;
  width: 100%;
  padding: 10px;
  .organization-left {
    width: 20%;
    border-right: 1px solid #ddd;
    margin-right: 20px;
    display: flex;
    flex-direction: column;
    .hcd {
      flex: 1;
      overflow: hiddongen;
      .tag-list {
        margin-top: 20px;
        margin-bottom: 40px;
        overflow-y: scroll;
        max-height: 500px;
        &::-webkit-scrollbar {
          width: 2px !important;
        }
        .el-tag {
          margin-right: 10px;
        }
      }
    }

    .btn-left {
      height: 40px;
      margin-bottom: 20px;
    }
  }
  .organization-right {
    flex: 1;
    .add-organization {
      margin-left: 40px;
      line-height: 20px;
      cursor: pointer;
      i {
        font-size: 18px;
        margin-right: 2px;
      }
    }
    .organization-search {
      margin-right: 20px;
      text-align: right;
    }
  }
}
</style>
