<template>
  <BaseContainer>
    <template slot="search-container">
      <el-form :inline="true">
        <el-form-item :label="$t('trials:site:table:siteId')">
          <el-input v-model="searchData.TrialSiteCode" style="width: 130px" clearable />
        </el-form-item>
        <!-- 中心 -->
        <el-form-item :label="$t('trials:site:table:site')">
          <el-input v-model="searchData.SiteName" style="width: 130px" clearable />
        </el-form-item>
        <!-- 参与者 -->
        <el-form-item :label="$t('trials:site:table:staff')">
          <el-input v-model="searchData.UserKeyInfo" style="width: 130px" clearable />
        </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 type="primary" v-hasPermi="['trials:trials-panel:site:verifyEmail']" @click="openCheckRemind">
            {{ $t('trials:site:button:checkRemind') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <template slot="main-container">
      <el-table v-adaptive="{ bottomOffset: 60 }" v-loading="loading" :data="list" stripe height="100"
        @sort-change="handleSortChange">
        <el-table-column type="index" width="40" align="left" />
        <!-- 中心编号 -->
        <el-table-column prop="TrialSiteCode" min-width="100" :label="$t('trials:site:table:siteId')"
          show-overflow-tooltip sortable="custom" />
        <!-- 中心名称 -->
        <el-table-column prop="TrialSiteName" min-width="100" :label="$t('trials:site:table:site')"
          show-overflow-tooltip sortable="custom" />
        <!-- 中心别名 -->
        <el-table-column prop="TrialSiteAliasName" min-width="100" :label="$t('trials:site:table:TrialSiteAliasName')"
          show-overflow-tooltip sortable="custom" />
        <!-- Subjects -->
        <el-table-column prop="SubjectCount" min-width="100" :label="$t('trials:site:table:subjects')"
          show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            <el-button v-if="scope.row.SubjectCount > 0 && hasSubjectRoute" type="text"
              @click="jumpToSubjectList(scope.row.TrialSiteId)">
              {{ scope.row.SubjectCount }}
            </el-button>
            <span v-else> {{ scope.row.SubjectCount }}</span>
          </template>
        </el-table-column>
        <!-- Visits -->
        <el-table-column prop="VisitCount" min-width="100" :label="$t('trials:site:table:visits')" show-overflow-tooltip
          sortable="custom">
          <template slot-scope="scope">
            <el-button v-if="scope.row.VisitCount > 0 && hasVisitRoute" type="text"
              @click="jumpToVisitList(scope.row.TrialSiteId)">
              {{ scope.row.VisitCount }}
            </el-button>
            <span v-else> {{ scope.row.VisitCount }}</span>
          </template>
        </el-table-column>
        <!-- Staff -->
        <el-table-column prop="UserCount" min-width="150" :label="$t('trials:site:table:staff')" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text" @click="getStaffList(scope.row)">
              {{
                scope.row.UserNameList.length > 0
                  ? scope.row.UserNameList.join(', ')
                  : ''
              }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="" min-width="150" fixed="right" :label="$t('common:action:action')" show-overflow-tooltip
          v-if="hasPermi(['trials:trials-panel:site:updateEmail'])">
          <template slot-scope="scope">
            <!-- 详情 -->
            <el-button icon="el-icon-message" circle :title="$t('trials:site:button:editEmail')"
              :disabled="!scope.row.IsHaveSiteSurveyRecord" v-hasPermi="['trials:trials-panel:site:updateEmail']"
              @click="openSiteEmail(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" />
    </template>
    <base-model v-if="crc_model.visible" :config="crc_model">
      <template slot="dialog-body">
        <el-table v-loading="userListLoading" :data="userList" height="400">
          <!-- Name -->
          <el-table-column prop="FullName" :label="$t('trials:site:table:name')" width="150" />
          <!-- User Type -->
          <el-table-column prop="UserType" :label="$t('trials:site:table:userType')" width="120"
            show-overflow-tooltip />
          <!-- Organization -->
          <el-table-column prop="OrganizationName" :label="$t('trials:site:table:organization')" width="150" />
          <!-- Phone -->
          <el-table-column prop="Phone" :label="$t('trials:site:table:phone')" show-overflow-tooltip sortable="custom"
            width="150" />
          <!-- Status -->
          <el-table-column prop="IsDeleted" :label="$t('trials:site:table:status')" show-overflow-tooltip sortable
            min-width="100">
            <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="UpdateTime" :label="$t('trials:site:table:dataAssigned')" show-overflow-tooltip
            sortable="custom" min-width="150" />
          <!-- 禁用时间 -->
          <el-table-column prop="DeletedTime" :label="$t('trials:site:table:deletedTime')" show-overflow-tooltip
            sortable min-width="150" />
        </el-table>
      </template>
    </base-model>
    <!--发送提醒核对中心人员邮件-->
    <base-model :config="checkRemind_model" v-if="checkRemind_model.visible">
      <template slot="dialog-body">
        <div class="tip">{{ $t('trials:site:checkRemind_form:tip:top') }}</div>
        <el-form ref="checkRemind_form" :model="checkRemind_form" :rules="rules" label-width="80px">
          <el-form-item :label="$t('trials:site:form:UserId')" prop="UserId">
            <el-select v-model="checkRemind_form.UserId" placeholder="" clearable style="width: 100%;"
              @change="handleSelectChange">
              <el-option v-for="item in checkUserList" :label="item.FullName" :key="item.Id" :value="item.Id">
                <div style="display: flex;justify-content: space-between;">
                  {{ item.FullName }}
                  <span style="color:#909399">{{ item.UserName }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('trials:site:form:UserName')">
            <el-input v-model="checkRemind_form.UserName" disabled />
          </el-form-item>
          <el-form-item :label="$t('trials:site:form:role')">
            <el-input v-model="checkRemind_form.Role" disabled />
          </el-form-item>
          <el-form-item :label="$t('trials:site:form:email')" prop="EMail">
            <el-input v-model="checkRemind_form.EMail" />
          </el-form-item>
          <el-form-item :label="$t('trials:site:form:phone')">
            <el-input v-model="checkRemind_form.Phone" disabled />
          </el-form-item>
        </el-form>
        <div class="tip">{{ $t('trials:site:checkRemind_form:tip:bottom') }}</div>
      </template>
      <template slot="dialog-footer">
        <el-button type="primary" @click="sendEMail" :loading="loading">
          {{ $t('common:button:confirm') }}
        </el-button>
        <el-button @click="checkRemind_model.visible = false" :loading="loading">
          {{ $t('common:button:cancel') }}
        </el-button>
      </template>
    </base-model>
    <!--发送中心人员更新邮件-->
    <base-model :config="siteEmail_model" v-if="siteEmail_model.visible">
      <template slot="dialog-body">
        <div class="tip">{{ siteEmail_tip }}</div>
        <el-form ref="siteEmail_form" :model="siteEmail_form" :rules="rules" label-width="80px">
          <el-form-item :label="$t('trials:site:form:UserName')">
            <el-input v-model="siteEmail_form.UserName" disabled />
          </el-form-item>
          <el-form-item :label="$t('trials:site:form:email')">
            <el-input v-model="siteEmail_form.OldEMail" disabled />
          </el-form-item>
          <el-form-item :label="$t('trials:site:form:phone')">
            <el-input v-model="siteEmail_form.Phone" disabled />
          </el-form-item>
          <div class="tip">{{ $t('trials:site:siteEmail_form:tip:bottom') }}</div>
          <el-form-item :label="$t('trials:site:form:FullName')">
            <el-input v-model="siteEmail_form.FullName" />
          </el-form-item>
          <el-form-item :label="$t('trials:site:form:email')">
            <el-input v-model="siteEmail_form.EMail" />
          </el-form-item>
        </el-form>

      </template>
      <template slot="dialog-footer">
        <el-button type="primary" @click="sendEMailTable" :loading="loading">
          {{ $t('common:button:confirm') }}
        </el-button>
        <el-button @click="siteEmail_model.visible = false" :loading="loading">
          {{ $t('common:button:cancel') }}
        </el-button>
      </template>
    </base-model>
  </BaseContainer>
</template>
<script>
import { getSiteCRCList, getTrialSiteCRCList, getMaintenanceList, sendCheckSiteSurveyUserEmail, sendUpdateSiteSurveyUserEmail, getTrialSiteLatestSurvey } from '@/api/trials'
import BaseContainer from '@/components/BaseContainer'
import BaseModel from '@/components/BaseModel'
import Pagination from '@/components/Pagination'
const searchDataDefault = () => {
  return {
    UserRealName: '',
    SiteName: '',
    SortField: 'TrialSiteCode',
    Asc: true,
    PageIndex: 1,
    PageSize: 20,
    TrialSiteCode: null,
  }
}
export default {
  name: 'SiteList',
  components: { BaseContainer, BaseModel, Pagination },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      crc_model: {
        visible: false,
        title: this.$t('trials:site:dialogTitle:staff'),
        width: '60%',
      },
      userListLoading: '',
      userList: [],
      trialId: '',
      hasSubjectRoute: false,
      hasVisitRoute: false,
      checkRemind_model: {
        visible: false,
        title: this.$t('trials:site:dialogTitle:checkRemind'),
        width: '30%',
      },
      listLoading: false,
      checkUserList: [],
      checkRemind_form: { UserId: null, UserName: null, Role: null, EMail: null, Phone: null },
      rules: {
        UserId: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        ],
        EMail: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
          {
            // type: 'email',
            //'Please input the correct email address'
            pattern: new RegExp(this.$reg().EmailRegexStr),
            message: this.$t("trials:site:ruleMessage:correctEmail"),
            trigger: ['blur'],
          },
        ]
      },
      siteEmail_model: {
        visible: false,
        title: this.$t('trials:site:dialogTitle:siteEmail'),
        width: '30%',
      },
      siteEmail_form: { TrialSiteId: null, UserId: null, UserName: null, Role: null, EMail: null, OldEMail: null, Phone: null, FullName: null },
      siteEmail_tip: null
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    const trialsRouter = this.$store.getters.routes.find(r => { return r.name === 'Trials' })
    const trialsPanelRouter = trialsRouter.children.find(r => { return r.name === 'TrialsPanel' }).children
    this.hasSubjectRoute = this.hasRoute('subject-list', trialsPanelRouter)
    this.hasVisitRoute = this.hasRoute('crc-upload', trialsPanelRouter)
    this.getList()
  },
  methods: {
    async sendEMail() {
      try {
        let validate = await this.$refs.checkRemind_form.validate()
        if (!validate) return false
        let data = {
          Email: this.checkRemind_form.EMail,
          FullName: this.checkRemind_form.FullName,
          TrialId: this.trialId

        }
        this.loading = true
        let res = await sendCheckSiteSurveyUserEmail(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t("trials:site:message:sendEmailSuccess"))
          this.checkRemind_model.visible = false
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    async sendEMailTable() {
      try {
        let validate = await this.$refs.siteEmail_form.validate()
        if (!validate) return false
        let data = {
          url: `${location.protocol}//${location.host}/researchLogin?trialId=${this.trialId}&lang=${this.$i18n.locale}&isUpload=1&email=${this.siteEmail_form.EMail}&oldEMail=${this.siteEmail_form.OldEMail}&trialSiteId=${this.siteEmail_form.TrialSiteId}`,
          Email: this.siteEmail_form.EMail || this.siteEmail_form.OldEMail,
          FullName: this.siteEmail_form.FullName || this.siteEmail_form.UserName,
          TrialSiteId: this.siteEmail_form.TrialSiteId

        }
        this.loading = true
        let res = await sendUpdateSiteSurveyUserEmail(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t("trials:site:message:sendEmailSuccess"))
          this.siteEmail_model.visible = false
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    handleSelectChange(id) {
      let find = this.checkUserList.find(item => item.Id === id)
      this.checkRemind_form.FullName = find.FullName
      this.checkRemind_form.UserName = find.UserName
      this.checkRemind_form.Role = find.TrialUserRoleList.filter(item => item.UserTypeEnum === 10 || item.UserTypeEnum === 12).map(item => item.UserTypeShortName).join(", ")
      this.checkRemind_form.EMail = find.EMail
      this.checkRemind_form.Phone = find.Phone
    },
    openCheckRemind() {
      this.getMaintenanceList()
      Object.keys(this.checkRemind_form).forEach(key => {
        this.checkRemind_form[key] = null
      })
      this.checkRemind_model.visible = true
    },
    openSiteEmail(row) {
      // this.getMaintenanceList()
      this.siteEmail_tip = this.$t('trials:site:siteEmail:tip:top').replace("xxx", `${row.TrialSiteCode}${row.TrialSiteName}`)
      Object.keys(this.siteEmail_form).forEach(key => {
        this.siteEmail_form[key] = null
      })
      this.getTrialSiteLatestSurvey(row.TrialSiteId)
      this.siteEmail_form.TrialSiteId = row.TrialSiteId
      this.siteEmail_model.visible = true
    },
    async getTrialSiteLatestSurvey(id) {
      try {
        let params = {
          TrialSiteId: id
        }
        let res = await getTrialSiteLatestSurvey(params)
        if (res.IsSuccess) {
          this.siteEmail_form.UserName = res.Result.UserName
          this.siteEmail_form.OldEMail = res.Result.Email
          // this.siteEmail_form.EMail = res.Result.Email
          this.siteEmail_form.Phone = res.Result.Phone
        }
      } catch (err) {
        console.log(err)
      }
    },
    getMaintenanceList() {
      this.listLoading = true
      let data = {
        PageIndex: 1,
        PageSize: 9999,
      }
      data.TrialId = this.trialId
      data.UserTypeList = [12, 10]
      getMaintenanceList(data)
        .then((res) => {
          this.listLoading = false
          this.checkUserList = res.Result.CurrentPageData
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      getSiteCRCList(this.searchData)
        .then((res) => {
          this.loading = false
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        })
        .catch(() => {
          this.loading = false
        })
    },
    getStaffList(row) {
      this.currentRow = { ...row }
      this.crc_model.visible = true
      this.userListLoading = true
      getTrialSiteCRCList(this.trialId, this.currentRow.TrialSiteId)
        .then((res) => {
          this.userListLoading = false
          this.userList = res.Result
        })
        .catch(() => {
          this.userListLoading = false
        })
    },
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    // 排序
    handleSortChange(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
    jumpToSubjectList(trialSiteId) {
      this.$router.push({ path: `/trials/trials-panel/subject/subject-list?trialId=${this.$route.query.trialId}&trialCode=${this.$route.query.trialCode}&researchProgramNo=${this.$route.query.researchProgramNo}&trialSiteId=${trialSiteId}` })
    },
    jumpToVisitList(trialSiteId) {
      this.$router.push({ path: `/trials/trials-panel/visit/crc-upload?trialId=${this.$route.query.trialId}&trialCode=${this.$route.query.trialCode}&researchProgramNo=${this.$route.query.researchProgramNo}&trialSiteId=${trialSiteId}` })
    },
    hasRoute(name, routeList) {
      for (let i = 0; i < routeList.length; i++) {
        if (routeList[i].name === name) {
          return true
        }
        if (routeList[i].children) {
          const flag = this.hasRoute(name, routeList[i].children)
          if (flag) {
            return flag
          }
        }
      }
      return false
    }
  },
}
</script>
<style lang="scss" scoped>
.tip {
  margin-bottom: 10px;
}
</style>
