<template>
  <div class="participant-list">
    <!-- 搜索框 -->
    <div class="filter-box">
      <el-form :inline="true">
        <!-- 姓名 -->
        <el-form-item :label="$t('trials:staff:table:name')">
          <el-input v-model="listQuery.UserRealName" class="mr" clearable />
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item :label="$t('trials:staff:table:uid')">
          <el-input v-model="listQuery.UserName" class="mr" clearable />
        </el-form-item>
        <!-- 用户类型 -->
        <el-form-item :label="$t('trials:staff:table:userType')">
          <el-select v-model="listQuery.UserTypeId" clearable class="mr">
            <el-option
              v-for="item of userTypeOptions"
              v-show="
                item.UserTypeEnum !== 8 &&
                item.UserTypeEnum !== 31 &&
                item.UserTypeEnum !== 26 &&
                item.UserTypeEnum !== 27
              "
              :key="item.Id"
              :label="item.UserTypeShortName"
              :value="item.Id"
            >
              <span>{{ item.UserType }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 单位 -->
        <el-form-item :label="$t('trials:staff:table:organization')">
          <el-input v-model="listQuery.OrganizationName" class="mr" clearable />
        </el-form-item>
        <!-- 状态 -->
        <el-form-item :label="$t('trials:staff:table:status')">
          <el-select v-model="listQuery.IsDeleted" clearable class="mr">
            <el-option
              v-for="item of $d.IsUserExitTrial"
              :label="item.label"
              :value="item.value"
              :key="item.id"
            />
            <!--            <el-option label="加入" :value="false" />-->
          </el-select>
        </el-form-item>
        <el-form-item>
          <!-- 查询 -->
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            {{ $t('common:button:search') }}
          </el-button>
          <!-- 重置 -->
          <el-button
            type="primary"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t('common:button:reset') }}
          </el-button>
          <!-- 添加系统用户 -->
          <el-button
            v-hasPermi="[
              'trials:trials-panel:setting:personnel-manage:add-internal-staff',
            ]"
            type="primary"
            style="margin-left: 10px"
            icon="el-icon-plus"
            @click="handleAdd('Add')"
          >
            {{ $t('trials:staff:button:addInternalStaff') }}
          </el-button>
          <!-- 添加外部人员 -->
          <el-button
            v-hasPermi="[
              'trials:trials-panel:setting:personnel-manage:add-external-staff',
            ]"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd('External')"
          >
            {{ $t('trials:staff:button:addExternalStaff') }}
          </el-button>
          <!-- 导出 -->
          <el-button
            type="primary"
            icon="el-icon-download"
            :disabled="list.length === 0"
            @click="handleExport"
          >
            {{ $t('common:button:export') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 项目参与人员列表 -->
    <el-table
      ref="settingList"
      v-loading="listLoading"
      :data="list"
      stripe
      @sort-change="handleSortByColumn"
    >
      <el-table-column type="index" width="50" />
      <!-- 姓名 -->
      <el-table-column
        prop="FullName"
        :label="$t('trials:staff:table:name')"
        show-overflow-tooltip
        sortable
        min-width="40"
      />
      <!-- 用户名 -->
      <el-table-column
        prop="UserName"
        :label="$t('trials:staff:table:uid')"
        show-overflow-tooltip
        sortable
        min-width="50"
      />
      <!-- 用户类型 -->
      <el-table-column
        prop="UserType"
        :label="$t('trials:staff:table:userType')"
        show-overflow-tooltip
        sortable
        width="140"
      >
        <template slot-scope="scope">
          <el-button
            v-if="
              Array.isArray(scope.row.TrialUserRoleList) &&
              scope.row.TrialUserRoleList.length > 0
            "
            type="text"
            @click.stop="openRoleList(scope.row)"
          >
            <span>{{
              scope.row.TrialUserRoleList.map(
                (item) => item.UserTypeShortName
              ).join(',')
            }}</span>
          </el-button>
        </template>
      </el-table-column>
      <!-- 联系电话 -->
      <el-table-column
        prop="Phone"
        :label="$t('trials:staff:table:phone')"
        show-overflow-tooltip
        sortable
        min-width="40"
      />
      <!-- 邮箱 -->
      <el-table-column
        prop="EMail"
        :label="$t('trials:staff:table:email')"
        show-overflow-tooltip
        sortable
        min-width="40"
      />
      <!-- 单位 -->
      <el-table-column
        prop="OrganizationName"
        :label="$t('trials:staff:table:organization')"
        sortable
        show-overflow-tooltip
        min-width="50"
      />
      <!-- 状态 -->
      <el-table-column
        prop="IsDeleted"
        :label="$t('trials:staff:table:status')"
        show-overflow-tooltip
        sortable
        min-width="40"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsDeleted" type="danger">{{
            $fd('IsUserExitTrial', scope.row.IsDeleted)
          }}</el-tag>
          <el-tag v-else>{{
            $fd('IsUserExitTrial', scope.row.IsDeleted)
          }}</el-tag>
        </template>
      </el-table-column>
      <!-- 加入日期 -->
      <el-table-column
        prop="JoinTime"
        :label="$t('trials:staff:table:joinTime')"
        show-overflow-tooltip
        sortable
        width="160"
      >
        <template slot-scope="scope">
          {{
            scope.row.JoinTime
              ? moment(scope.row.JoinTime).format('YYYY-MM-DD')
              : ''
          }}
        </template>
      </el-table-column>
      <!-- 退出日期 -->
      <el-table-column
        prop="RemoveTime"
        :label="$t('trials:staff:table:exitTime')"
        show-overflow-tooltip
        sortable
        width="160"
      >
        <template slot-scope="scope">
          {{
            scope.row.RemoveTime
              ? moment(scope.row.RemoveTime).format('YYYY-MM-DD')
              : ''
          }}
        </template>
      </el-table-column>
      <!-- 授权时间 -->
      <!-- <el-table-column
        prop="CreateTime"
        :label="$t('trials:staff:table:authorizationTime')"
        show-overflow-tooltip
        sortable
        width="180"
      /> -->
      <!-- 禁用时间 -->
      <!-- <el-table-column
        prop="DeletedTime"
        :label="$t('trials:staff:table:disableTime')"
        show-overflow-tooltip
        sortable
        min-width="60"
      /> -->

      <el-table-column
        v-if="hasPermi(['trials:trials-panel:setting:personnel-manage:status'])"
        :label="$t('common:action:action')"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['trials:trials-panel:setting:personnel-manage:status']"
            circle
            :title="$t('trials:staff:action:status')"
            icon="el-icon-edit-outline"
            :disabled="
              hasPermi(['role:pm']) && scope.row.UserTypeEnum * 1 === 1
            "
            @click="handleStatus(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination" style="text-align: right">
      <pagination
        :total="total"
        :page.sync="listQuery.PageIndex"
        :limit.sync="listQuery.PageSize"
        @pagination="getList"
      />
    </div>

    <!-- 分配参与人员模态框 -->
    <base-model v-if="staff_model.visible" :config="staff_model">
      <template slot="dialog-body">
        <StaffForm v-if="isAdd == 'Add'" @closeDialog="closeDialog" />
        <StaffExternalForm
          v-else
          @closeDialog="closeDialog"
          @getList="getList"
        />
      </template>
    </base-model>

    <!-- 修改参与者人员状态 -->
    <base-model v-if="status_model.visible" :config="status_model">
      <template slot="dialog-body">
        <el-form
          ref="statusForm"
          :model="statusForm"
          label-width="110px"
          size="small"
          :rules="statusRules"
        >
          <!-- Status -->
          <el-form-item
            :label="$t('trials:staff:table:status')"
            prop="isDeleted"
          >
            <el-radio-group
              v-model="statusForm.isDeleted"
              @change="handleIsDeletedChanged"
            >
              <el-radio
                v-for="item of $d.IsUserExitTrial"
                :label="item.value"
                :key="item.id"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 退出日期 -->
          <el-form-item
            v-if="statusForm.isDeleted"
            :label="$t('trials:staff:table:exitTime')"
            prop="removeTime"
          >
            <el-date-picker
              v-model="statusForm.removeTime"
              type="date"
              :picker-options="pickerOption"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </el-form-item>
          <!-- 加入日期 -->
          <el-form-item
            v-else
            :label="$t('trials:staff:table:joinTime')"
            prop="joinTime"
          >
            <el-date-picker
              v-model="statusForm.joinTime"
              type="date"
              :picker-options="pickerOption"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"
            />
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-footer">
        <el-button
          :disabled="btnLoading"
          size="small"
          type="primary"
          @click="status_model.visible = false"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          size="small"
          type="primary"
          :loading="btnLoading"
          @click="saveStatus"
        >
          {{ $t('common:button:save') }}
        </el-button>
      </template>
    </base-model>
    <!-- 修改参与者人员角色 -->
    <base-model v-if="role_model.visible" :config="role_model">
      <template slot="dialog-body">
        <el-table :data="roleList" style="width: 100%" max-height="300px">
          <el-table-column type="index" width="40" />
          <el-table-column
            prop="UserTypeShortName"
            :label="
              $t(
                'trials:trials-panel:setting:personnel-manage:table:UserTypeShortName'
              )
            "
          />
          <el-table-column
            prop="IsDeleted"
            :label="
              $t(
                'trials:trials-panel:setting:personnel-manage:table:IsUserRoleDisabled'
              )
            "
          >
            <template slot-scope="scope">
              <span> {{ $fd('IsEnable', !scope.row.IsDeleted) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="IsDeleted"
            :label="
              $t(
                'trials:trials-panel:setting:personnel-manage:table:enableTime'
              )
            "
            min-width="120px"
          >
            <template slot-scope="scope">
              <span v-if="!scope.row.IsDeleted">
                {{ scope.row.UpdateTime }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="IsDeleted"
            :label="
              $t(
                'trials:trials-panel:setting:personnel-manage:table:forbiddenTime'
              )
            "
            min-width="120px"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.IsDeleted">
                {{ scope.row.UpdateTime }}
              </span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('common:action:action')" width="120px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.IsDeleted"
                @click.stop="changeRoleStatus(scope.row, true)"
              >
                {{ $fd('IsEnable', false) }}
              </el-button>
              <el-button
                size="mini"
                type="text"
                :disabled="!scope.row.IsDeleted"
                @click.stop="changeRoleStatus(scope.row, false)"
              >
                {{ $fd('IsEnable', true) }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </base-model>
  </div>
</template>
<script>
import {
  getMaintenanceList,
  getTrialUserTypeList,
  updateTrialUser,
  trialUserListExport,
  updateTrialUserRole,
} from '@/api/trials'
import Pagination from '@/components/Pagination'
import StaffForm from './staffForm'
import StaffExternalForm from './staffExternalForm'
import BaseModel from '@/components/BaseModel'
import moment from 'moment'
const getListQueryDefault = () => {
  return {
    UserRealName: '',
    UserName: '',
    UserTypeId: '',
    OrganizationName: '',
    IsDeleted: null,
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'Staff',
  components: { Pagination, StaffForm, BaseModel, StaffExternalForm },
  data() {
    return {
      list: [],
      listQuery: getListQueryDefault(),
      listLoading: false,
      total: 0,
      staff_model: {
        visible: false,
        title: this.$t('trials:staff:dialogTitle:add'),
        width: '1200px',
      },
      status_model: {
        visible: false,
        title: this.$t('trials:staff:dialogTitle:status'),
        width: '500px',
      },
      userTypeOptions: [],
      isAdd: 'Add',
      staffStatus: null,
      btnLoading: false,
      currentRow: {},
      trialId: '',
      moment,
      statusForm: { isDeleted: false, removeTime: '', joinTime: '' },
      statusRules: {
        removeTime: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur'],
          },
        ],
        joinTime: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur'],
          },
        ],
      },
      pickerOption: {
        disabledDate: (time) => {
          return time.getTime() > Date.now()
        },
      },

      roleList: [],
      role_model: {
        visible: false,
        title: this.$t('trials:staff:dialogTitle:role'),
        width: '800px',
      },
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getUserType()
    this.getList()
  },
  methods: {
    // 修改角色状态
    async changeRoleStatus(row, status) {
      try {
        let message = this.$t('trials:staff:comfirm:changeRoleStatus').replace(
          'xxx',
          this.$fd('IsEnable', !status)
        )
        let comfirm = await this.$confirm(message)
        if (!comfirm) return false
        let data = {
          IdList: [row.Id],
          IsDeleted: status,
        }
        let res = await updateTrialUserRole(data)
        if (res.IsSuccess) {
          row.IsDeleted = status
          this.$message.success(
            this.$t('trials:trials-myinfo:message:updateSuccessfully')
          )
          this.getList()
        }
      } catch (err) {
        console.log(err)
      }
    },
    openRoleList(row) {
      this.roleList = row.TrialUserRoleList
      this.role_model.visible = true
    },
    // 分页获取项目参与人员列表
    getList() {
      this.listLoading = true
      this.listQuery.TrialId = this.trialId
      getMaintenanceList(this.listQuery)
        .then((res) => {
          this.listLoading = false
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 新增项目参与者
    handleAdd(type) {
      if (type === 'Add') {
        this.staff_model.title = this.$t('trials:staff:button:addInternalStaff')
      } else {
        this.staff_model.title = this.$t('trials:staff:button:addExternalStaff')
      }
      this.staff_model.visible = true
      this.isAdd = type
    },
    handleStatus(row) {
      const { IsDeleted, RemoveTime, JoinTime } = { ...row }
      this.currentRow = { ...row }
      this.statusForm.isDeleted = IsDeleted
      this.statusForm.removeTime = RemoveTime
      this.statusForm.joinTime = JoinTime
      this.status_model.visible = true
    },
    // 修改参与者状态
    saveStatus() {
      this.$refs.statusForm.validate((valid) => {
        if (!valid) return
        this.btnLoading = true
        const param = {
          id: this.currentRow.Id,
          trialId: this.trialId,
          isDeleted: this.statusForm.isDeleted,
          removeTime: this.statusForm.removeTime,
          joinTime: this.statusForm.joinTime,
        }
        updateTrialUser(param)
          .then((res) => {
            this.btnLoading = false
            if (res.IsSuccess) {
              this.status_model.visible = false
              this.getList()
              this.$message.success(this.$t('common:message:savedSuccessfully'))
            }
          })
          .catch(() => {
            this.btnLoading = false
          })
      })
    },
    handleIsDeletedChanged(val) {
      if (val) {
        this.statusForm.joinTime = ''
      } else {
        this.statusForm.removeTime = ''
      }
    },
    // 查询
    handleSearch() {
      this.listQuery.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.listQuery = getListQueryDefault()
      this.getList()
    },
    // 排序
    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()
    },
    // 关闭模态框并更新列表
    closeDialog() {
      this.staff_model.visible = false
      this.$message.success(this.$t('common:message:savedSuccessfully'))
      this.getList()
    },
    // 导出
    handleExport() {
      this.listLoading = true
      this.listQuery.TrialId = this.trialId
      trialUserListExport({ ...this.listQuery })
        .then((data) => {
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    // 获取用户类型下拉数据
    getUserType() {
      getTrialUserTypeList().then((res) => {
        this.userTypeOptions = res.Result
      })
    },
  },
}
</script>
<style lang="scss">
.participant-list {
  .filter-box {
    display: flex;
    padding: 5px;
    .base-search-form {
      .el-form-item {
        margin-bottom: 0px;
      }
    }
    .mr {
      margin-right: 5px;
      width: 120px;
    }
  }
  .el-dialog__header {
    padding: 10px;
  }
  .el-dialog__body {
    padding: 10px;
  }
}
</style>
