<template>
  <el-container class="participant-container">
    <el-header style="height:50px">
      <div class="filter-container">
        <!-- 姓名 -->
        <span>{{ $t('trials:externalStaff:table:name') }}:</span>
        <el-input :maxLength="$inputMax" v-model="listQuery.Name" size="mini" class="mr" clearable />
        <!-- 邮箱 -->
        <span>{{ $t('trials:externalStaff:table:email') }}:</span>
        <el-input :maxLength="$inputMax" v-model="listQuery.Email" size="mini" class="mr" clearable />
        <!-- 电话 -->
        <span>{{ $t('trials:externalStaff:table:phone') }}:</span>
        <el-input :maxLength="$inputMax" v-model="listQuery.Phone" size="mini" class="mr" clearable />
        <!-- 查询 -->
        <el-button type="primary" size="mini" icon="el-icon-search" @click="handleSearch">
          {{ $t('common:button:search') }}
        </el-button>
        <!-- 重置 -->
        <el-button size="mini" type="primary" icon="el-icon-refresh-left" @click="handleReset">
          {{ $t('common:button:reset') }}
        </el-button>
        <!-- 发送邮件 -->
        <el-button type="primary" size="mini" style="margin-left:auto" :disabled="selectArr.length === 0" :loading="assignLoadStatus" icon="el-icon-message" @click="sendEmail">
          {{ $t('trials:staff:button:sendEmail') }}
        </el-button>
        <!-- 添加 -->
        <el-button type="primary" icon="el-icon-plus" size="mini" style="margin-left:10px" :loading="assignLoadStatus" @click="handleAdd">
          {{ $t('common:button:add') }}
        </el-button>
      </div>
    </el-header>
    <el-main>
      <div class="data-table">
        <el-table
          v-loading="loading"
          :data="list"
          stripe
          height="400px"
          class="participant-table-list"
          @selection-change="handleSelectChange"
          @sort-change="handleSortByColumn"
        >
          <el-table-column
            type="selection"
            width="50"
            :selectable="handleSelectable"
          />
          <el-table-column type="index" width="50" />
          <el-table-column
            prop="UserRealName"
            :label="$t('trials:externalStaff:table:name')"
            show-overflow-tooltip
            sortable="custom"
            min-width="100"
          >
            <template slot-scope="scope">{{ scope.row.LastName + '/' + scope.row.FirstName }}</template>
          </el-table-column>
          <el-table-column
            prop="UserType"
            :label="$t('trials:externalStaff:table:userType')"
            show-overflow-tooltip
            sortable="custom"
            min-width="120"
          >
            <template slot-scope="scope">
              {{ userTypeOptions.length > 0 ? userTypeOptions.find((v) => { return v.Id == scope.row.UserTypeId }).UserTypeShortName : '' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="Phone"
            :label="$t('trials:externalStaff:table:phone')"
            show-overflow-tooltip
            sortable="custom"
            min-width="120"
          />
          <el-table-column
            prop="Email"
            :label="$t('trials:externalStaff:table:email')"
            show-overflow-tooltip
            sortable="custom"
            min-width="120"
          />
          <el-table-column
            prop="OrganizationName"
            :label="$t('trials:externalStaff:table:organization')"
            show-overflow-tooltip
            sortable="custom"
            min-width="120"
          />

          <el-table-column
            prop="inviteState"
            :label="$t('trials:externalStaff:table:status')"
            fixed="right"
            show-overflow-tooltip
            sortable="custom"
            min-width="120"
          >
            <template slot-scope="scope">{{ $fd('IsJoin', scope.row.IsJoin) }}</template>
          </el-table-column>
          <el-table-column :label="$t('common:action:action')" fixed="right" min-width="150">
            <template slot-scope="scope">
              <el-button
                circle
                icon="el-icon-delete"
                :title="$t('trials:externalStaff:button:delete')"
                @click="deleteTrialExternalUser(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <StaffExternalAdd ref="StaffExternalAdd" :user-type-options="userTypeOptions" @getList="refeshList" />
  </el-container>
</template>
<script>
import { getTrialExternalUserList, addTrialUsers, getUserTypeList, sendExternalUserJoinEmail } from '@/api/trials'
import { deleteTrialExternalUser } from '@/api/trials/setting.js'
import StaffExternalAdd from './staffExternalAdd'
const getListQueryDefault = () => {
  return {
    Phone: '',
    Email: '',
    Name: ''
  }
}
export default {
  components: { StaffExternalAdd },
  data() {
    return {
      list: [],
      loading: false,
      listQuery: getListQueryDefault(),
      selectArr: [],
      assignLoadStatus: false,
      isAdmin: JSON.parse(zzSessionStorage.getItem('IsAdmin')),
      userTypeOptions: [],
      stateList: ['WaitSent', 'HasSend', 'UserConfirmed', 'UserReject', 'OverTime'],
      trialId: ''
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getUserType()
    this.getList()
  },
  methods: {
    refeshList() {
      this.getList()
      this.$emit('getList')
    },
    isSendEmail(row) {
      console.log(row)
    },
    handleEdit(row) {
      this.$nextTick(() => {
        this.$refs['StaffExternalAdd'].openDialog(this.$t('trials:externalStaff:dialogTitle:edit'), row)
      })
    },
    handleAdd() {
      this.$nextTick(() => {
        this.$refs['StaffExternalAdd'].openDialog(this.$t('trials:externalStaff:dialogTitle:add'), {})
      })
    },
    deleteTrialExternalUser(row) {
      this.$confirm(this.$t('trials:externalStaff:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          deleteTrialExternalUser(row.Id, row.IsSystemUser, row.SystemUserId)
            .then(res => {
              this.$message.success(this.$t('common:message:deletedSuccessfully'))
              this.getList()
              this.loading = false
            }).catch(() => { this.loading = false })
        })
    },
    sendEmail() {
      const loading = this.$loading({
        target: document.querySelector('.participant-table-list'),
        fullscreen: false,
        lock: true
      })
      // var BaseUrl = document.domain + `/#/login`
      var BaseUrl = `${location.protocol}//${location.host}/login`
      var joinUrl = `${location.protocol}//${location.host}/email-recompose`
      var sendEmailUserArr = this.selectArr.map((v) => { return { Id: v.Id, Email: v.Email, IsSystemUser: v.IsSystemUser, SystemUserId: v.SystemUserId } })
      sendExternalUserJoinEmail({
        TrialId: this.trialId,
        SendUsers: sendEmailUserArr,
        BaseUrl: BaseUrl,
        RouteUrl: joinUrl
      }).then(() => {
        loading.close()
        this.$message.success(this.$t('common:message:savedSuccessfully'))
        this.getList()
        this.$emit('getList')
      }).catch(() => { loading.close() })
    },
    getList() {
      const loading = this.$loading({
        target: document.querySelector('.participant-table-list'),
        fullscreen: false,
        lock: true
      })
      this.listQuery.TrialId = this.trialId
      getTrialExternalUserList(this.listQuery).then(res => {
        loading.close()
        this.list = res.Result
      }).catch(() => { loading.close() })
    },
    handleAssign() {
      this.$confirm(this.$t('trials:externalStaff:message:add'), {
        type: 'warning',
        distinguishCancelAndClose: true
      }).then(() => {
        const loading = this.$loading({
          target: document.querySelector('.participant-table-list'),
          fullscreen: false,
          lock: true
        })
        this.assignLoadStatus = true
        addTrialUsers(this.selectArr)
          .then(res => {
            this.assignLoadStatus = false
            loading.close()
            if (res.IsSuccess) {
              this.$emit('closeDialog')
              this.$message.success(this.$t('common:message:savedSuccessfully'))
            }
          }).catch(() => {
            loading.close()
            this.assignLoadStatus = false
          })
      })
    },
    handleSearch() {
      this.listQuery.PageIndex = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = getListQueryDefault()
      this.getList()
    },
    handleSelectChange(val) {
      this.selectArr = val
    },
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.listQuery.Asc = true
      } else {
        this.listQuery.Asc = false
      }
      this.listQuery.SortField = column.prop
      this.listQuery.PageIndex = 1
      this.getList()
    },
    handleSelectable(row) {
      if (row.State === 0 || row.State === 4 || row.State === 3) {
        return true
      } else {
        return false
      }
    },
    getUserType() {
      getUserTypeList(1).then(res => {
        this.userTypeOptions = res.Result
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .participant-container{
    height: 100%;
    .el-header{
      .filter-container{
        display: flex;
        align-items: center;
        span{
          font-size:13px;
          margin-right:5px;
        }
        .mr{
          margin-right: 5px;
          width: 120px;
        }
      }
    }
    .el-main{
      padding: 0px;
    }
    .el-footer{
      padding: 0 20px;
    }
  }
</style>
