<template>
  <div>
    <Row align="middle" type="flex">
      <Select class="searchItem" style="width:200px;margin-top: 2px;" v-model="orgTypeForSearch">
        <Option :key="index" :value="item.val" v-for="(item, index) in modelNameArr">{{ item.name }}</Option>
      </Select>
      <AutoComplete
        class="searchItem"
        placeholder="姓名/工号"
        style="width:200px;"
        v-model="nameCode"
      ></AutoComplete>
      <!-- <AutoComplete class="searchItem" placeholder="所属中心" style="width:200px;" v-model="siteName"></AutoComplete>
      <AutoComplete
        class="searchItem"
        placeholder="所属专线"
        style="width:200px;"
        v-model="activityName"
      ></AutoComplete>
      <AutoComplete class="searchItem" placeholder="所属业务小组" style="width:200px;" v-model="teamName"></AutoComplete>-->
      <Button :loading="loading" @click="searchUser" class="mg-set" type="primary">查询</Button>
      <div class="table_data-control">
        <Button @click="InfoAdd" ghost icon="md-add" type="primary">新增</Button>
      </div>
    </Row>
    <br />
    <Table :columns="columnsDaily" :data="dataLibrary" :loading="loading" border ref="selection"></Table>
    <Page
      :current.sync="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      :total="total"
      @on-change="pageChange"
      class="mt-set16"
      show-total
    />

    <Modal
      :footer-hide="false"
      :mask-closable="false"
      :title="titleName"
      :width="550"
      @on-ok="ok"
      @on-visible-change="closeWin"
      v-model="isShowModal"
    >
      <Row>
        <span style="color: #17233d;font-weight: bold">用户职位:</span>
        <Select
          @on-change="changeOrgType"
          style="margin:0 15px 0 5px;width:150px"
          v-model="orgType"
        >
          <Option
            :key="index"
            :value="item.val"
            v-for="(item, index) in modelNameArr"
          >{{ item.name }}</Option>
        </Select>

        <span style="color: #17233d;font-weight: bold">用户:</span>
        <Input
          :maxlength="20"
          :readonly="true"
          :value="userName"
          @on-focus="showUserModal"
          class="tables-edit-input"
          style="width:160px;margin:0 15px 0 5px;"
        />
      </Row>
      <br />
      <Tree
        :data="treeDatas"
        :load-data="loadData"
        :multiple="isMultiple"
        @on-select-change="getSelectNode"
        @on-toggle-expand="handleExpand"
      ></Tree>
      <Row :style="{display:isShowLoader}">
        <Col class="demo-spin-col" span="8">
          <Spin fix>
            <Icon class="demo-spin-icon-load" size="18" type="ios-loading"></Icon>
            <div>Loading</div>
          </Spin>
        </Col>
      </Row>
      <br />
      <Row align="middle" type="flex">
        <Input :maxlength="100" class="tables-edit-input" placeholder="备注" v-model="remark" />
      </Row>
      <div slot="footer">
        <Button @click="isShowModal=false" size="large" type="text">取消</Button>
        <Button
          :loading="editLoading"
          @click="ok"
          size="large"
          type="primary"
        >{{isAddAction?'添加':'修改'}}</Button>
      </div>
    </Modal>

    <Modal
      :footer-hide="true"
      :mask-closable="false"
      :width="850"
      :z-index="userMoldaIndex"
      title="选择用户"
      v-model="isShowUserModal"
    >
      <user-list @confirmSelect="confirmSelectUser" ref="userList"></user-list>
    </Modal>

    <Modal
      :footer-hide="true"
      :mask-closable="false"
      :width="850"
      @on-visible-change="closeOrgList"
      title="用户信息查看"
      v-model="isShowInfoModal"
    >
      <org-range-list :userInfo="userInfo"></org-range-list>
    </Modal>
  </div>
</template>

<script>
import commonList from '@/mixin/commonList'
import WfmOrgAPI from '@api/common/wfmOrg'
import configValue from '@conf/index'
import userList from './user-list'
import orgRangeList from './org-range-list'

export default {
  name: 'org-relation',

  mixins: [commonList],
  data () {
    return {
      idsToCommit: '',
      isShowLoader: 'none',
      isShowInfoModal: false,
      userInfo: null,
      remark: '',
      orgTypeForSearch: '',
      activityName: '',
      siteName: '',
      nameCode: '',
      teamName: '',
      userMoldaIndex: 9999,
      titleName: '',
      isMultiple: false,
      loading: false,
      isShowModal: false,
      orgType: -1,
      userName: '',
      userNum: '',
      isShowUserModal: false,
      setForids: new Set(),
      orgRangeMap: null,
      editLoading: false,
      modelNameArr: [
        {
          val: '',
          name: '请选择职位'
        },
        {
          val: configValue.LEADER_TYPE.SCHEDUE_LEADER,
          name: '排班师'
        },
        {
          val: configValue.LEADER_TYPE.ANAGER_LEADER,
          name: '经理'
        },
        {
          val: configValue.LEADER_TYPE.REGION_LEADER,
          name: '助经'
        },
        {
          val: configValue.LEADER_TYPE.ITEAM_LEADER,
          name: '组长'
        },
        {
          val: configValue.LEADER_TYPE.CHECK_LEADER,
          name: '考勤员'
        },
        // {
        //   val: configValue.LEADER_TYPE.PERFORMANCE_LEADER,
        //   name: '绩效员'
        // }
      ],
      columnsDaily: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center'
        },
        {
          title: '姓名/工号',
          key: 'name',
          render (h, params) {
            return h('div', params.row.map.orgUserName)
          }
        },
        {
          title: '用户职位',
          key: '',
          width: 150,
          render (h, params) {
            return h('div', params.row.map.orgType)
          }
        },
        {
          title: '组织类型',
          key: 'center',
          width: 100,
          render (h, params) {
            return h('div', params.row.map.rangeType)
          }
        },
        {
          title: '组织范围',
          key: 'center',
          render (h, params) {
            return h('div', params.row.map.rangeList)
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.userInfo = params.row
                      this.isShowInfoModal = true
                    }
                  }
                },
                '查看用户'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'success',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.InfoEdit(params.row)
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    transfer: true,
                    title: '确定删除吗？'
                  },
                  on: {
                    'on-ok': () => {
                      this.delete(params.row.uuid)
                    }
                  }
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        'margin-left': '4px'
                      },
                      props: {
                        type: 'warning',
                        size: 'small'
                      }
                    },
                    '删除'
                  )
                ]
              )
            ])
          }
        }
      ],
      dataLibrary: [],
      treeDatas: [],
      confirmedUser: null,
      isShowSearchList: false,
      selectTreeNodes: [],
      isAddAction: false,
      marinRecUuid: '',
      selectCenter: null
    }
  },
  components: { userList, orgRangeList },
  watch: {
    selectCenter (newCenter, oldCenter) {
      if (oldCenter === null || newCenter === null) {
        return
      }
      this.confirm(newCenter, oldCenter)
    }
  },
  methods: {
    confirm (newCenter, oldCenter) {
      this.$Modal.confirm({
        title: '更换数据中心',
        content: '<p style="color:green">数据中心将被更改</p>',
        onOk: () => {
          this.reSetTreePartData(oldCenter)
          this.$Message.destroy()
          this.$Message.warning('数据中心已更改')
          this.selectTreeNodes = []
          this.idsToCommit = ''
          oldCenter.expand = false
        },
        onCancel: () => {
          newCenter.expand = false
          oldCenter.expand = true
          this.selectCenter = oldCenter
        }
      })
    },
    reSetTreePartData (oldCenter) {
      if (oldCenter === null) {
        return
      }
      let children = oldCenter.children
      if (children !== [] && children !== null && children.length > 0) {
        children.forEach(el => {
          el.selected = false
          let children = el.children
          if (children === undefined) {
            return
          }
          if (children !== [] && children !== null && children.length > 0) {
            children.forEach(el => {
              el.selected = false
            })
          }
        })
      }
    },
    handleExpand (item) {
      if (item.key.charAt(0) === 's') {
        this.selectCenter = item
      }
    },
    ok () {
      this.isShowLoader = 'none'
      this.commitDatas(this.userNum, this.orgType, this.isAddAction)
    },
    cancel () {
      this.$Message.info('Clicked cancel')
    },
    changeOrgType () {
      this.treeDatas = []
      this.orgRangeMap = {}
      this.selectTreeNodes = []
      this.selectCenter = null
      this.idsToCommit = ''
      if (this.orgType > 0) {
        this.showTree(this.orgType)
      }
    },
    showUserModal () {
      this.isShowUserModal = true
      this.$refs.userList.nameCode = ''
      this.$refs.userList.teamName = ''
      this.$refs.userList.siteName = ''
      //this.$refs.userList.searchForm.pageNum = 1
    },
    // 表格操作-新增
    InfoAdd (row) {
      this.titleName = '新增机构'
      this.isShowModal = true
      this.isAddAction = true
      this.treeDatas = []
      this.orgType = -1
      this.userName = ''
      this.userNum = ''
      this.remark = ''
      this.orgRangeMap = {}
      this.selectTreeNodes = []
      this.selectCenter = null
      this.isShowLoader = 'none'
      this.idsToCommit = ''
    },
    InfoEdit (row) {
      this.isAddAction = false
      this.titleName = '编辑机构'
      this.isShowModal = true
      this.orgType = row.orgType
      this.userName = row.orgUser.map.userName
      let uuid = row.orgUser.userNum
      this.userNum = uuid
      this.orgRangeMap = null
      this.marinRecUuid = row.uuid
      this.remark = row.remark
      this.orgRangeMap = {}
      this.selectTreeNodes = []
      this.selectCenter = null
      this.isShowLoader = 'block'
      this.idsToCommit = ''
      WfmOrgAPI.view(row.uuid).then(({ data }) => {
        this.treeDatas = []
        if (data.data !== undefined && data.data !== null) {
          const list = data.data.orgRangeList
          this.initTreeData(list)
        }
      })
    },
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    // 查询
    doSearch () {
      this.loading = true
      this.dataLibrary = []
      this.$nextTick(() => {
        WfmOrgAPI.viewList({ ...this.searchForm })
          .then(({ data }) => {
            this.loading = false
            if (data.status === 'success') {
              this.total = data.data.total
              this.dataLibrary = data.data.list
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },

    showTree (stopFlag) {
      this.queryTreeData(null, this.treeDatas)
    },
    loadData (item, callback) {
      const data = []
      this.queryTreeData(item.key, data)
      setTimeout(() => {
        callback(data)
      }, 500)
    },
    /**
     *stopFlag:领导类型（排班师1经理2助理区部负责人3组长4）
     *elementArray:数组,当为根节点时为[], 为子节点时为children[{children:[]}]
     */
    queryTreeData (parentId, elementArray) {
      WfmOrgAPI.orgTree({ parentId }).then(({ data }) => {
        if (
          data.data === undefined ||
          data.data === null ||
          data.data.length === 0
        ) {
          return
        }
        const list = data.data
        list.forEach(element => {
          const isContinue = this.handConntinueFun(this.orgType, element.id)
          const config = (h, { root, node, data }) => {
            // ture 表示了该用户所对应树的叶子节点，只有叶子节点是可选的
            return h(
              'span',
              {
                style: {
                  color: '#999'
                }
              },
              data.title
            )
          }
          let tmp = {
            title: element.name,
            key: element.id,
            render: isContinue ? config : null
          }
          if (isContinue) {
            tmp.loading = false
            tmp.children = []
          }
          elementArray.push(tmp)
        })
      })
    },
    async initTreeData (list) {
      if (list === undefined || list === null || list.length === 0) {
        this.isShowLoader = 'none'
        return
      }
      let leafNodeMapForSelected = {}

      for (let index in list) {
        let ele = list[index]
        let orgId = ele.map.rangeId
        this.idsToCommit += orgId + ';'
        this.idsToCommit = this.idsToCommit.substring(
          0,
          this.idsToCommit.length
        )
        leafNodeMapForSelected[ele.map.rangeId] = true
        let id = await this.getNodeParentId(ele.map.rangeId)
        if (id !== undefined && id !== null && id !== '') {
          this.setForids.add(id)
        }
      }
      this.setData(leafNodeMapForSelected)
    },
    async setData (leafNodeMapForSelected) {
      let childrenMap = {}
      const config = (h, { root, node, data }) => {
        // ture 表示了该用户所对应树的叶子节点，只有叶子节点是可选的
        return h(
          'span',
          {
            style: {
              color: '#999'
            }
          },
          data.title
        )
      }

      while (this.setForids.size !== 0) {
        var it = this.setForids.values()
        let tmpParentId = it.next().value
        if (
          tmpParentId === undefined ||
          tmpParentId === null ||
          tmpParentId === ''
        ) {
          this.isShowLoader = 'none'
          break
        }

        let data = await this.getTree(tmpParentId)

        if (
          data.data === undefined ||
          data.data === null ||
          data.data.length === 0
        ) {
          this.isShowLoader = 'none'
          return
        }

        const children = []
        data.data.forEach(ele => {
          const isContinue = this.handConntinueFun(this.orgType, ele.id)
          let tmp = {
            title: ele.name,
            key: ele.id,
            expand: false,
            selected: leafNodeMapForSelected[ele.id],
            render: isContinue ? config : null
          }

          if (isContinue) {
            tmp.loading = false
            tmp.children = []
          }

          if (childrenMap[ele.id] !== undefined) {
            let tmpChildren = childrenMap[ele.id]
            tmp.children = tmpChildren
            tmp.expand = true
            if (tmp.key.charAt(0) === 's') {
              this.selectCenter = tmp
            }
            delete childrenMap[ele.id]
          }
          children.push(tmp)
        })

        childrenMap[tmpParentId] = children
        this.setForids.delete(tmpParentId)

        let id = await this.getNodeParentId(tmpParentId)
        tmpParentId = id
        if (id !== undefined && id !== null && id !== '') {
          this.setForids.add(id)
        }
      }

      this.treeDatas = childrenMap['0']
      this.isShowLoader = 'none'
    },
    getTree (tmpParentId) {
      return new Promise((resolve, reject) => {
        WfmOrgAPI.orgTree({
          parentId: tmpParentId === '0' ? null : tmpParentId
        })
          .then(data => {
            resolve(data.data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    getNodeParentId (treeId) {
      return new Promise((resolve, reject) => {
        WfmOrgAPI.orgTreeInfo({ treeId })
          .then(data => {
            if (data.data.data.length > 0) {
              resolve(data.data.data[0].parentId)
            } else {
              resolve(null)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    handMultiChoose (stopFlag) {
      const leadTeype = configValue.LEADER_TYPE
      // (b_业务单元-s_中心-a_专线-t_业务小组)

      if (stopFlag === leadTeype.SCHEDUE_LEADER) {
        // 排班师
        this.isMultiple = false
      }

      if (stopFlag === leadTeype.ANAGER_LEADER) {
        // 经理

        this.isMultiple = true
      }

      if (stopFlag === leadTeype.REGION_LEADER) {
        // 助理（区部负责人）

        this.isMultiple = true
      }

      if (stopFlag === leadTeype.ITEAM_LEADER) {
        // 组长
        this.isMultiple = false
      }

      if (stopFlag === leadTeype.CHECK_LEADER) {
        // 考勤员
        this.isMultiple = false
      }

      // if (stopFlag === leadTeype.PERFORMANCE_LEADER) {
      //   // 绩效员
      //   this.isMultiple = false
      // }
    },
    handConntinueFun (stopFlag, centerId) {
      const leadTeype = configValue.LEADER_TYPE
      // (b_业务单元-s_中心-a_专线-t_业务小组)

      if (centerId.includes('agent')) {
        return false
      }

      if (stopFlag === leadTeype.SCHEDUE_LEADER) {
        // 排班师

        if (centerId.charAt(0) === 's') {
          this.isMultiple = false
          return false
        }
      }

      if (stopFlag === leadTeype.ANAGER_LEADER) {
        // 经理

        if (centerId.charAt(0) === 'a') {
          this.isMultiple = true
          return false
        }
      }

      if (stopFlag === leadTeype.REGION_LEADER) {
        // 助理（区部负责人）

        if (centerId.charAt(0) === 't') {
          this.isMultiple = true
          return false
        }
      }

      if (stopFlag === leadTeype.ITEAM_LEADER) {
        // 组长

        if (centerId.charAt(0) === 't') {
          this.isMultiple = false
          return false
        }
      }

      if (stopFlag === leadTeype.CHECK_LEADER) {
        // 考勤员

        if (centerId.charAt(0) === 's') {
          this.isMultiple = false
          return false
        }
      }

      // if (stopFlag === leadTeype.PERFORMANCE_LEADER) {
      //   // 绩效员

      //   if (centerId.charAt(0) === 's') {
      //     this.isMultiple = false
      //     return false
      //   }
      // }

      return true
    },
    confirmSelectUser (row) {
      this.confirmedUser = row
      this.isShowSearchList = false
      this.isShowUserModal = false
      this.userName = row.name
      this.userNum = row.code
    },
    searchUser () {
      this.confirmedUser = null
      this.isShowSearchList = true
      this.searchForm.nameCode = this.nameCode.trim()
      this.searchForm.siteName = this.siteName.trim()
      this.searchForm.teamName = this.teamName.trim()
      this.searchForm.activityName = this.activityName.trim()
      this.searchForm.orgType = this.orgTypeForSearch
      this.doInitSearch()
    },
    getSelectNode (nodes) {
      this.selectTreeNodes = nodes
    },
    commitDatas (leaderCode = '', orgType = -1, isAddAction = true) {
      if (leaderCode === '') {
        this.$Message.destroy()
        this.$Message.warning('未选择用户')
        return
      }

      if (orgType < 0 || orgType === '') {
        this.$Message.destroy()
        this.$Message.warning('请选择职位')
        return
      }

      // if (this.selectTreeNodes.length === 0) {
      //   this.$Message.error('至少选择一条数据')
      //   return
      // }

      let ids = ''
      this.selectTreeNodes.forEach(ele => {
        ids += `${ele.key};`
      })
      if (ids.length > 0) {
        ids = ids.substring(0, ids.length - 1)
        this.idsToCommit = ids
      }

      if (
        ids === '' &&
        (this.idsToCommit === null || this.idsToCommit.length === 0)
      ) {
        this.$Message.destroy()
        this.$Message.warning('至少选择一条数据')
        return
      }

      const result = {
        map: {
          leaderCode: leaderCode,
          rangIds: this.idsToCommit
        },
        remark: this.remark,
        orgType: orgType,
        uuid: this.marinRecUuid
      }

      this.editLoading = true
      if (isAddAction) {
        WfmOrgAPI.create(result)
          .then(({ data }) => {
            if (data.status === 'success') {
              this.$Message.destroy()
              this.$Message.success('新增成功')
              this.isShowModal = false
              this.doInitSearch()
            }
            this.editLoading = false
          })
          .catch(() => {
            this.editLoading = false
          })
      } else {
        WfmOrgAPI.update(result)
          .then(({ data }) => {
            if (data.status === 'success') {
              this.$Message.destroy()
              this.$Message.success('修改成功')
              this.isShowModal = false
              this.doInitSearch()
            }
            this.editLoading = false
          })
          .catch(() => {
            this.editLoading = false
          })
      }
      this.marinRecUuid = ''
    },
    delete (uuid) {
      if (uuid === undefined || uuid === '' || uuid === null) {
        return
      }
      WfmOrgAPI.remove({ uuid }).then(({ data }) => {
        if (data.status === 'success') {
          this.$Message.destroy()
          this.$Message.success('删除成功')
          this.doInitSearch()
        }
      })
    },
    closeWin (e) {
      if (!e) {
        this.treeDatas = []
        this.selectCenter = null
        this.treeDatas = []
        this.setForids.clear()
        this.idsToCommit = ''
      }
    },
    closeOrgList (e) {
      if (!e) {
        this.userInfo = null
      }
    }
  }
}
</script>

<style lang="less">
.dynamic_panle {
  .ivu-form-item-label {
    width: 60px !important;
  }
  .ivu-form-item-content {
    margin-left: 60px !important;
  }
  .add-item {
    margin-top: 4px;
  }
  .close-item {
    margin-top: 4px;
  }
}
.mg-set {
  margin: 0 12px 0 8px;
}
.long-label {
  .ivu-form-item-label {
    width: 96px !important;
  }
}
.ivu-table-wrapper {
  .ivu-icon {
    left: 25px;
  }
}

.ivu-tree {
  .ivu-tree-title {
    color: rgb(23, 35, 61);
    font-weight: bold;
  }

  .ivu-tree-title-selected,
  .ivu-tree-title-selected:hover {
    background-color: #b50029;
    //background-color: #17508A;
    color: white;
  }
}
.searchItem {
  margin-right: 10px;
}

.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.demo-spin-col {
  height: 50px;
  position: relative;
}
</style>
