<template>
  <BaseContainer>
    <template slot="search-container">
      <div style="margin-left: auto">
        <!-- 提交 -->
        <el-button
          type="primary"
          :disabled="submitIdArr.length == 0"
          icon="el-icon-check"
          :loading="loading"
          @click="handleSubmit"
        >
          {{ $t('trials:seletctedReviews:button:submit') }}
        </el-button>
        <!-- 下载所有 -->
        <el-button
          v-if="hasPermi(['role:pm'])"
          type="primary"
          icon="el-icon-download"
          :disabled="!total"
          :loading="loading"
          @click="handleDownloadAll"
        >
          {{ $t('trials:seletctedReviews:button:submissionDownAll') }}
        </el-button>
      </div>
    </template>
    <template slot="main-container">
      <el-table
        v-loading="listLoading"
        v-adaptive="{ bottomOffset: 65 }"
        height="100"
        :data="list"
        class="table"
        :row-class-name="handleHighLighRow"
        @sort-change="handleSortChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="handleSelectTable" />
        <el-table-column type="index" width="40" />
        <!-- Name -->
        <el-table-column
          prop="LastName"
          :label="$t('trials:seletctedReviews:table:name')"
          show-overflow-tooltip
          sortable="custom"
          min-width="120"
        >
          <template slot-scope="scope">
            <span
              style="color: #428bca; cursor: pointer"
              @click="
                go(
                  `/trialsResume?doctorId=${scope.row.Id}&trialId=${$route.query.trialId}&token=${token}`
                )
              "
              >{{ scope.row.LastName }} / {{ scope.row.FirstName }}</span
            >
            <!-- <el-button type="text" @click="go(`/trialsResume?doctorId=${scope.row.Id}&token=${token}`)">{{ scope.row.LastName }} / {{ scope.row.FirstName }}</el-button> -->
          </template>
        </el-table-column>
        <!-- Name CN -->
        <el-table-column
          v-if="!isEN"
          prop="ChineseName"
          :label="$t('trials:seletctedReviews:table:nameCN')"
          show-overflow-tooltip
          sortable="custom"
          min-width="120"
        />
        <!-- ID -->
        <el-table-column
          prop="Code"
          :label="$t('trials:seletctedReviews:table:id')"
          show-overflow-tooltip
          sortable="custom"
          min-width="100"
        />
        <!-- Status -->
        <el-table-column
          prop="DoctorTrialState"
          :label="$t('trials:seletctedReviews:table:status')"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.DoctorTrialState === 5" type="primary">{{
              $fd('DoctorTrialState', scope.row.DoctorTrialState)
            }}</el-tag>
            <el-tag v-else type="danger">{{
              $fd('DoctorTrialState', 16)
            }}</el-tag>
          </template>
        </el-table-column>
        <!-- Submitter -->
        <el-table-column
          prop="OptUserName"
          :label="$t('trials:seletctedReviews:table:submitter')"
          min-width="120"
        />
        <!-- Submission Time -->
        <el-table-column
          prop="OptTimeStr"
          :label="$t('trials:seletctedReviews:table:submissionTime')"
          min-width="150"
        />
        <el-table-column
          :label="$t('common:action:action')"
          fixed="right"
          width="200"
        >
          <template slot-scope="scope">
            <!-- <el-button type="primary" icon="el-icon-view" @click="handleDetail(scope.row)">Detail</el-button> -->
            <el-button
              icon="el-icon-download"
              circle
              :title="$t('trials:seletctedReviews:button:submissionDown')"
              @click="handleDownload(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="page"
        :total="total"
        :page.sync="listQuery.PageIndex"
        :limit.sync="listQuery.PageSize"
        @pagination="getList"
      />

      <el-dialog
        :title="$t('trials:seletctedReviews:title:language')"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <!-- 语言 -->
        <span>{{ $t('trials:seletctedReviews:label:language') }}: </span>
        <el-radio-group v-model="language">
          <el-radio :label="2">English</el-radio>
          <el-radio :label="1">中文</el-radio>
        </el-radio-group>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">{{
            $t('common:button:cancel')
          }}</el-button>
          <el-button type="primary" @click="handleDownloadResumes">{{
            $t('common:button:save')
          }}</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseContainer>
</template>
<script>
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import {
  getSubmissionOrApprovalReviewerList,
  submitReviewer,
  downloadResume,
} from '@/api/trials'
import { getTrialDoctorOfficialResume } from '@/api/reviewers'
import store from '@/store'
import axios from 'axios'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
const enrollState = 1
export default {
  name: 'Submission',
  components: { BaseContainer, Pagination },
  props: {
    isEN: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      list: [],
      listQuery: {
        TrialId: '',
        IntoGroupSearchState: enrollState,
        PageIndex: 1,
        PageSize: 20,
        Asc: false,
        SortField: '',
      },
      loading: false,
      total: 0,
      listLoading: false,
      submitIdArr: [],
      dialogVisible: false,
      language: 2,
      token: store.getters.token,
      selectTable: {},
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    go(path) {
      window.open(path)
    },
    initPage() {
      this.getList()
    },
    getList() {
      this.listLoading = true
      this.listQuery.TrialId = this.$route.query.trialId
      getSubmissionOrApprovalReviewerList(this.listQuery)
        .then((res) => {
          this.listLoading = false
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
          // eslint-disable-next-line handle-callback-err
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleSubmit() {
      // 是否确认提交？
      this.$confirm(this.$t('trials:seletctedReviews:message:msg2'), {
        type: 'warning',
      }).then(() => {
        this.loading = true
        const trialId = this.$route.query.trialId
        submitReviewer(trialId, this.submitIdArr, 1)
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.getList()
              // 保存成功
              this.$message.success(this.$t('common:message:savedSuccessfully'))
              if (res.Result.IsHaveSPMOrCPM) {
                this.$emit('nextStep', 'approval')
              } else {
                this.$emit('nextStep', 'confirmation')
              }
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    handleSelectionChange(val) {
      const arr = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].Id)
      }
      this.submitIdArr = arr
    },
    handleSortChange(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()
    },
    handleHighLighRow({ row, rowIndex }) {
      if (row.DoctorTrialState === 5) {
        return 'selected'
      }
    },
    handleSelectTable(row) {
      return row.DoctorTrialState !== 5
    },
    handleDetail(row) {
      const { href } = this.$router.resolve({
        path: `/trialsResume?doctorId=${row.Id}&trialId=${this.$route.query.trialId}`,
      })
      window.open(href, '_blank')
    },
    handleDownloadAll() {
      // 英文环境直接下载
      if (process.env.NODE_ENV === 'usa') {
        this.language = 2
        this.handleDownloadResumes()
      } else {
        this.dialogVisible = true
      }
    },
    getFileData(fileUrl) {
      return new Promise((resolve, reject) => {
        axios(fileUrl, {
          method: 'GET',
          responseType: 'blob', // 返回的数据会被强制转为blob类型 ，转换成arraybuffer 也行
        })
          .then((res) => {
            console.log('res', res)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    async handleBatchDown(dataSource) {
      return new Promise((resolve) => {
        console.log('开始压缩')
        const zip = new JSZip() // 创建实例对象
        const promises = []
        dataSource.FileList.forEach((item) => {
          console.log(this.OSSclientConfig.basePath + item.Path)
          const promise = this.getFileData(
            this.OSSclientConfig.basePath + item.Path
          ).then((res) => {
            const fileName = item.FileName + ''
            // 创建文件用file()，创建文件夹用 floder()
            zip.file(fileName, res.data, { binary: true })
          })
          promises.push(promise)
        })
        console.log(promises)
        // 生成 zip 文件
        Promise.all(promises)
          .then(() => {
            // 生成zip 文件
            zip
              .generateAsync({
                type: 'blob',
                compression: 'DEFLATE', // STORE: 默认不压缩， DEFLATE：需要压缩
                compressionOptions: {
                  level: 9, // 压缩等级 1~9   1 压缩速度最快， 9 最优压缩方式
                },
              })
              .then((res) => {
                saveAs(res, dataSource.ReviewerCode + '_Sub.zip') // 使用FileSaver.saveAs保存文件，文件名可自定义
                resolve()
              })
          })
          .catch((reason) => {
            resolve()
          })
      })
    },
    handleDownloadResumes() {
      getTrialDoctorOfficialResume({
        doctorIdList: this.selectTable.Id
          ? [this.selectTable.Id]
          : this.list.map((v) => {
              return v.Id
            }),
        language: this.language,
      })
        .then(async (res) => {
          this.selectTable = {}
          this.dialogVisible = false
          if (!res.Result || res.Result.length === 0) {
            this.$alert(this.$t('trials:seletctedReviews:table:noResume'))
          } else {
            for (let i = 0; res.Result.length > i; i++) {
              let item = res.Result[i]
              await this.handleBatchDown(item)
            }
          }
        })
        .catch((err) => {
          this.dialogVisible = false
          this.selectTable = {}
        })
      // this.dialogVisible = false
      // const arr = []
      // for (let index = 0; index < this.list.length; index++) {
      //   arr.push(this.list[index].Id)
      // }
      // this.downloadResume(arr)
    },
    downloadResume(arr) {
      downloadResume(this.$route.query.trialId, this.language, arr).then(
        (res) => {
          window.open(res.Result)
        }
      )
    },
    handleDownload(row) {
      this.selectTable = row
      // 英文环境直接下载
      if (process.env.NODE_ENV === 'usa') {
        this.language = 2
        this.handleDownloadResumes()
      } else {
        this.dialogVisible = true
      }
    },
  },
}
</script>

