<!-- 调整人员Edit -->
<template>
  <div class="adjustPersonEdit">
    <dialog-edit :visible.sync="dialogVisible" :editModel="editModel"
                 :footerVisible="false"
                 :form="form" :api="api" :width="width" :autoSave="autoSave"
                 :title="$t('enterpriseInfoManage.organization.adjustPerson')"
                 :appendToBody="appendToBody">
      <div class="transfer-class">
        <el-transfer :filter-method="filterMethod" ref="trans" v-model="value" :data="sourceData" :titles="[$t('enterpriseInfoManage.organization.allPerson'),
                   $t('enterpriseInfoManage.organization.currentPerson')]" @change="change" :props="defaultProps" filterable>
        </el-transfer>
      </div>
      <div class="buttonGroupCenter">
        <auth-button :disabled="disabled" size="" type="primary" :label="$t('common.save')" :loading="loading" @click="onSaved"></auth-button>
        <auth-button size="" :label="$t('common.close')" @click="dialogVisible = false"></auth-button>
      </div>
    </dialog-edit>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import { DialogEdit, authButton } from 'newepoch-components'
import organizationApi from '@/api/enterpriseInfoManage/organizationApi.js'
export default {
  extends: new BaseEdit(),
  name: 'adjustPersonEdit',
  props: {
    openModel: {
      type: String,
      required: true,
      default: function () {
        return ''
      }
    }
  },
  components: {
    DialogEdit,
    authButton
  },
  data () {
    return {
      disabled: true,
      width: '1000px',
      autoSave: false,
      loading: false,
      appendToBody: true,
      saveForm: {
        accountId: [],
        list: [],
        orgId: '',
        posId: ''
      },
      sourceData: [],
      // 原始数据，判断是否移动人员
      originalValue: [],
      value: [],
      valueList: [],
      defaultProps: {
        key: 'accountId',
        label: 'nickName'
      }
    }
  },
  computed: {
    api () {
      return organizationApi.person
    },
    authorApi () {
      return organizationApi.author
    },
    adjustApi () {
      return organizationApi.position
    }
  },
  methods: {
    filterMethod (query, item) {
      let str = query.trim()
      return item.nickName.indexOf(str) > -1
    },
    equalStr (val1, val2) {
      val1.sort()
      val2.sort()
      return JSON.stringify(val1) === JSON.stringify(val2)
    },
    change () {
      this.disabled = this.equalStr(this.originalValue, this.value)
    },
    // clearQuery () {
    //   return 'left | right'
    // },
    // 保存
    onSaved () {
      let $this = this
      if ($this.openModel === 'position') {
        $this.saveForm.accountId = $this.value
        $this.loading = true
        $this.adjustApi.updatePositionByAccount($this.saveForm).then(res => {
          if (res && res.data) {
            $this.success(this.$i18n.messages[this.$i18n.locale].enterpriseInfoManage.organization.adjustSuc)
            $this.loading = false
            $this.dialogVisible = false
            $this.$emit('refreshTable')
          }
        }).catch(() => {
          $this.loading = false
        })
      } else if ($this.openModel === 'org') {
        $this.saveForm.accountId = $this.value
        for (let i = 0; i < $this.value.length; i++) {
          for (let j = 0; j < $this.sourceData.length; j++) {
            if ($this.value[i] === $this.sourceData[j].accountId) {
              let p = {
                account: '',
                accountId: '',
                nickName: '',
                mobile: '',
                leaderFlag: '0'
              }
              var a = $this.valueList.filter(item => $this.value[i] === item.accountId)
              if (a.length > 0) {
                if (a[0].leaderFlag === '') {
                  p.leaderFlag = '0'
                } else {
                  p.leaderFlag = a[0].leaderFlag
                }
              }
              let arr = $this.sourceData[j].nickName.split('-')
              p.account = $this.sourceData[j].account
              p.accountId = $this.sourceData[j].accountId
              p.nickName = arr[0]
              p.mobile = $this.sourceData[j].mobile
              $this.saveForm.list.push(p)
            }
          }
        }
        $this.loading = true
        $this.api.adjustPerson($this.saveForm).then(res => {
          if (res && res.data) {
            $this.success(this.$i18n.messages[this.$i18n.locale].enterpriseInfoManage.organization.adjustSuc)
            $this.loading = false
            $this.dialogVisible = false
            $this.$emit('refreshTable')
          }
        }).catch(() => {
          $this.loading = false
        })
      }
    },
    // 加载当前组织机构下的所有人员
    loadOrgPerson (paras) {
      let $this = this
      $this.api.getList(paras).then(res => {
        if (res && res.data) {
          $this.sourceData = res.data
          $this.sourceData.forEach(item => {
            if (!this.UtilJs.isEmpty(item.mobile)) {
              item.nickName = item.nickName + '-' + item.mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
            }
          })
        }
      })
    },
    // 加载当前租户下所有用户列表
    loadUserByTenant () {
      let $this = this
      $this.authorApi.getList({ orgId: $this.form.keyId }).then(res => {
        if (res && res.data) {
          res.data.forEach(it => {
            let p = {
              account: '',
              accountId: '',
              nickName: '',
              mobile: ''
            }
            if (!this.UtilJs.isEmpty(it.mobile)) {
              it.nickName = it.nickName + '-' + it.mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
            }
            p.mobile = it.mobile
            p.account = it.userName
            p.accountId = it.userId
            p.nickName = it.nickName
            $this.sourceData.push(p)
          })
        }
      })
    }
  },
  watch: {
    visible (val) {
      let $this = this
      if (val) {
        $this.$nextTick(() => {
          if (this.openModel === 'position') {
            let p = {
              orgId: ''
            }
            p.orgId = $this.form.orgId
            $this.loadOrgPerson(p)
            $this.form.list.forEach(it => {
              $this.value.push(it.accountId)
            })
            $this.originalValue = JSON.parse(JSON.stringify($this.value))
            $this.saveForm.posId = $this.form.keyId
            $this.saveForm.orgId = $this.form.orgId
          } else if (this.openModel === 'org') {
            $this.loadUserByTenant()
            $this.api.getList({ orgId: $this.form.keyId }).then(res => {
              if (res && res.data) {
                res.data.forEach(it => {
                  $this.value.push(it.accountId)
                  $this.valueList.push({ accountId: it.accountId, leaderFlag: it.leaderFlag })
                })
                $this.originalValue = JSON.parse(JSON.stringify($this.value))
              }
            })
            $this.saveForm.orgId = $this.form.keyId
          }
        })
      } else {
        $this.disabled = true
        $this.$refs['trans'].clearQuery('left')
        $this.$refs['trans'].clearQuery('right')
        $this.value = []
        $this.sourceData = []
        $this.originalValue = []
        $this.saveForm.accountId = []
        $this.saveForm.list = []
        $this.valueList = []
        $this.saveForm.orgId = ''
        $this.saveForm.posId = ''
        $this.disabled = true
      }
    }
  }
}
</script>

<style scoped lang="scss">
</style>
