<template>
  <BaseContainer>
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 文件名称 -->
        <el-form-item :label="$t('trials:data-sync:fileList:fileName')" prop="FileName">
          <el-input v-model="searchData.FileName" size="small" clearable style="width: 120px" />
        </el-form-item>
        <!-- 文件类型 -->
        <el-form-item :label="$t('trials:data-sync:fileList:fileType')" prop="FileType">
          <el-input v-model="searchData.FileType" size="small" clearable style="width: 120px" />
        </el-form-item>
        <!-- 源区域 -->
        <el-form-item :label="$t('trials:data-sync:fileList:uploadRegion')" prop="UploadRegion">
          <el-select v-model="searchData.UploadRegion" style="width: 120px">
            <el-option
              v-for="item in regionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 源可用时间 -->
        <el-form-item :label="$t('trials:data-sync:fileList:uploadTimeRange')">
          <el-date-picker
            v-model="uploadTimeRange"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="handleUploadtimeChange"
            style="width: 300px"
            type="datetimerange">
          </el-date-picker>
        </el-form-item>
        <!-- 目标区域 -->
        <el-form-item :label="$t('trials:data-sync:fileList:targetRegion')" prop="TargetRegion">
          <el-select v-model="searchData.TargetRegion" style="width: 120px">
            <el-option
              v-for="item in regionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 目标可用时间 -->
        <el-form-item :label="$t('trials:data-sync:fileList:syncTimeRange')">
          <el-date-picker
            v-model="SyncTimeRange"
            :default-time="['00:00:00', '23:59:59']"
            value-format="yyyy-MM-dd HH:mm:ss"
            @change="handleSynctimeChange"
            style="width: 300px"
            type="datetimerange">
          </el-date-picker>
        </el-form-item>
        <!-- 优先级 -->
         <el-form-item :label="$t('trials:data-sync:fileList:priority')">
          <el-input v-model="searchData.Priority" clearable style="width: 120px"></el-input>
        </el-form-item>
        <!-- 是否同步完成 -->
        <el-form-item :label="$t('trials:data-sync:fileList:isSync')" prop="IsSync">
          <el-select v-model="searchData.IsSync" clearable style="width: 120px">
            <el-option 
              v-for="item of $d.YesOrNo"
              :key="'IsSync' + item.label" 
              :value="item.value" 
              :label="item.label" 
            />
          </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 type="primary" icon="el-icon-edit" :disabled="selectedRows.length === 0" @click="handleBatchEdit">
            {{ $t('trials:data-sync:fileList:batchEdit') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <template slot="main-container">
      <el-table v-loading="loading" v-adaptive="{ bottomOffset: 70 }" height="100" :data="list"
        class="table" @sort-change="handleSortByColumn" :default-sort="{ prop: 'CreateTime', order: 'descending' }" @selection-change="handleSelectionChange">
        <el-table-column type="index" width="50" />
        <el-table-column type="selection" width="50" :selectable="selectableRow"/>
        <el-table-column :label="$t('trials:data-sync:fileList:fileName')" prop="FileName" min-width="90" show-overflow-tooltip sortable="custom">
        </el-table-column>
        <el-table-column :label="$t('trials:data-sync:fileList:fileSize')" prop="FileSize" min-width="90" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ fileSizeFormatter(scope.row.FileSize) }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('trials:data-sync:fileList:fileType')" prop="FileType" min-width="90" show-overflow-tooltip sortable="custom">
        </el-table-column>
        
        <el-table-column :label="$t('trials:data-sync:fileList:uploadRegion')" prop="UploadRegion" min-width="90" show-overflow-tooltip sortable="custom" />
        
        <el-table-column :label="$t('trials:data-sync:fileList:createTime')" prop="CreateTime" min-width="120" show-overflow-tooltip sortable="custom" />
        <el-table-column :label="$t('trials:data-sync:fileList:filePath')" prop="Path" min-width="90" show-overflow-tooltip sortable="custom" />
        <el-table-column :label="$t('trials:data-sync:fileList:isNeedSync')" prop="IsNeedSync" min-width="120" show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsNeedSync" type="success">
              {{ $fd('YesOrNo', scope.row.IsNeedSync) }}
            </el-tag>
            <el-tag v-else type="danger">
              {{ $fd('YesOrNo', scope.row.IsNeedSync) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('trials:data-sync:fileList:targetRegion')" prop="TargetRegion" min-width="100" show-overflow-tooltip sortable="custom" />
        <el-table-column :label="$t('trials:data-sync:fileList:syncFinishedTime')" prop="SyncFinishedTime" min-width="120" show-overflow-tooltip sortable="custom" />
        <el-table-column :label="$t('trials:data-sync:fileList:priority')" prop="Priority" min-width="80" show-overflow-tooltip sortable="custom" />
        <el-table-column :label="$t('trials:data-sync:fileList:isSync')" prop="IsSync" min-width="120" show-overflow-tooltip sortable="custom">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsSync" type="success">
              {{ $fd('YesOrNo', scope.row.IsSync) }}
            </el-tag>
            <el-tag v-else type="danger">
              {{ $fd('YesOrNo', scope.row.IsSync) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('trials:data-sync:fileList:updateTime')" prop="UpdateTime" min-width="120" show-overflow-tooltip sortable="custom" />
        <el-table-column :label="$t('common:action:action')" width="240" show-overflow-tooltip fixed="right">
          <template slot-scope="scope">
            <!-- 详情 -->
            <el-button type="primary" size="mini"  @click="handleOpenTaskTable(scope.row)">
              {{ $t('trials:data-sync:fileList:detail') }}
            </el-button>
            <!-- 重新同步 -->
            <el-button type="primary" size="mini" :disabled="!scope.row.IsNeedSync || !scope.row.IsSync" @click="execute(scope.row)">
              {{ $t('trials:data-sync:fileList:reExecute') }}
            </el-button>
            <el-button type="primary" size="mini" :disabled="scope.row.IsSync" @click="handleEdit(scope.row)">
              {{ $t('common:action:edit') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" />
    </template>
    <el-dialog v-if="editDialogVisible" :title="$t('trials:data-sync:fileList:edit')" :visible.sync="editDialogVisible" width="600px" :close-on-click-modal="false" append-to-body>
      <el-form ref="editFormRef" :model="editForm" :rules="editRules" label-width="110px" v-loading="formLoading">
        <el-form-item :label="$t('trials:data-sync:fileList:fileName')">
          <el-input v-model="editForm.FileName" disabled />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:fileSize')">
          <el-input :value="fileSizeFormatter(editForm.FileSize)" disabled />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:fileType')">
          <el-input v-model="editForm.FileType" disabled />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:uploadRegion')">
          <el-input v-model="editForm.UploadRegion" disabled />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:targetRegion')">
          <el-input v-model="editForm.TargetRegion" disabled />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:isNeedSync')" prop="IsNeedSync">
          <el-select v-model="editForm.IsNeedSync" style="width: 100%">
            <el-option
              v-for="item of $d.YesOrNo"
              :key="'IsNeedSync' + item.label"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item :label="$t('trials:data-sync:fileList:updateTime')">
          <el-input v-model="editForm.UpdateTime" disabled />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:filePath')">
          <el-input v-model="editForm.Path" type="textarea" :rows="2" disabled />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:priority')" prop="Priority">
          <el-input-number v-model="editForm.Priority" :min="0" :controls="true" style="width: 100%" />
        </el-form-item>
        <el-form-item :label="$t('trials:data-sync:fileList:isSync')" prop="IsSync">
          <el-select v-model="editForm.IsSync" style="width: 100%" disabled>
            <el-option
              v-for="item of $d.YesOrNo"
              :key="'IsSync' + item.label"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">{{ $t('common:button:cancel') }}</el-button>
        <el-button type="primary" @click="handleSaveEdit">{{ $t('common:button:save') }}</el-button>
      </span>
    </el-dialog>
    <el-dialog v-if="batchEditDialogVisible" :title="$t('trials:data-sync:fileList:batchEdit')" :visible.sync="batchEditDialogVisible" width="300px" :close-on-click-modal="false" append-to-body>
      <el-form ref="batchEditFormRef" :model="batchEditForm" :rules="batchEditRules" label-width="80px" v-loading="formLoading">
        <el-form-item :label="$t('trials:data-sync:fileList:priority')" prop="Priority">
          <el-input-number v-model="batchEditForm.Priority" :min="0" :controls="true" style="width: 100%" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchEditDialogVisible = false">{{ $t('common:button:cancel') }}</el-button>
        <el-button type="primary" @click="handleSaveBatchEdit">{{ $t('common:button:save') }}</el-button>
      </span>
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getFileUploadRecordList, addOrUpdateFileUploadRecord, batchAddSyncFileTask } from '@/api/file'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import moment from 'moment'
const searchDataDefault = () => {
  return {
    TrialId: '',
    DataFileType: null,
    SubjectCode: '',
    VisitName: '',
    StudyCode: '',
    FileName: '',
    UploadRegion: null,
    TargetRegion: null,
    IsSync: null,
    UploadStartTime: null,
    UploadEndTime: null,
    SyncFinishedStartTime: null,
    SyncFinishedEndTime: null,
    Priority: null,
    Asc: false,
    SortField: 'UpdateTime',
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'FileList',
  components: { BaseContainer, Pagination },
  props: {
    rowInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    dataFileType: {
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      moment,
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      loading: false,
      uploadTimeRange: null,
      SyncTimeRange: null,
      regionOptions: [
        {
          value: 'CN',
          label: 'CN'
        }, {
          value: 'US',
          label: 'US'
        }
      ],
      editDialogVisible: false,
      editForm: {
        // Priority: null,
        // IsSync: null,
      },
      editRules: {
        Priority: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'change' }],
        IsSync: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: 'change' }],
      },
      formLoading: false,
      selectedRows: [],
      batchEditDialogVisible: false,
      batchEditForm: {
        Priority: null,
      },
      batchEditRules: {
        Priority: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'change' }],
      },
    }
  },
  mounted() {
    
    this.getList()
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        this.searchData.TrialId = this.$route.query.trialId
        if (Object.keys(this.rowInfo).length !== 0) {
          this.searchData.SubjectCode = this.rowInfo.SubjectCode
          this.searchData.VisitName = this.rowInfo.VisitName
          this.searchData.StudyCode = this.rowInfo.StudyCode
        }
        
        this.searchData.DataFileType = this.dataFileType
        let res = await getFileUploadRecordList(this.searchData)
        this.loading = false
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
      } catch(e) {
        this.loading = false
        console.log(e)
      }
    },
    handleOpenTaskTable(row) {
      this.$emit('openTaskTable', row)
    },
    handleEdit(row) {
      this.editForm = {...row}
      this.editDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.editFormRef) this.$refs.editFormRef.clearValidate()
      })
    },
    async handleSaveEdit() {
      try {
        let valid = await this.$refs.editFormRef.validate()
        if (!valid) return
        this.formLoading = true
        let res = await addOrUpdateFileUploadRecord(this.editForm)
        this.formLoading = false
        if (res.IsSuccess) {
          this.editDialogVisible = false
          this.getList()
        }
      } catch(e) {
        console.log(e)
        this.formLoading = false
      }
    },
    async execute(row) {
      try {
        this.loading = true
        let params = {
          fileUploadRecordIdList: [row.Id]
        }
        let res = await batchAddSyncFileTask(params)
        if (res.IsSuccess) {
          this.$message.success(this.$t('trials:data-sync:msg:executeSuccessfully'))
        }
        this.loading = false
        this.getList()
      } catch(e) {
        this.loading = false
        console.log(e)
      }
      
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    selectableRow(row) {
      return !row.IsSync
    },
    handleBatchEdit() {
      if (!this.selectedRows.length) return
      this.batchEditForm = {
        Priority: null,
      }
      this.batchEditDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.batchEditFormRef) this.$refs.batchEditFormRef.clearValidate()
      })
    },
    async handleSaveBatchEdit() {
      try {
        let valid = await this.$refs.batchEditFormRef.validate()
        if (!valid) return
        this.formLoading = true
        let params = {
          fileUploadRecordIdList: this.selectedRows,
          priority: this.editForm.Priority
        }
        let res = await batchAddSyncFileTask(params)
        this.formLoading = false
        if (res.IsSuccess) {
          this.batchEditDialogVisible = false
          this.getList()
        }
      } catch(e) {
        console.log(e)
        this.formLoading = false
      }
    },
    fileSizeFormatter(size) {
      if (!size) return
      return (size / Math.pow(1024, 2)).toFixed(3) + 'MB'
    },
    handleUploadtimeChange(val) {
      if (val) {
        this.searchData.UploadStartTime = val[0]
        this.searchData.UploadEndTime = val[1]
      } else {
        this.searchData.UploadStartTime = ''
        this.searchData.UploadEndTime = ''
      }
    },
    handleSynctimeChange(val) {
      if (val) {
        this.searchData.SyncFinishedStartTime = val[0]
        this.searchData.SyncFinishedEndTime = val[1]
      } else {
        this.searchData.SyncFinishedStartTime = ''
        this.searchData.SyncFinishedEndTime = ''
      }
    },
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置列表查询
    handleReset() {
      this.uploadTimeRange = null
      this.handleUploadtimeChange()
      this.SyncTimeRange = null
      this.handleSynctimeChange()
      this.searchData = searchDataDefault()
      this.getList()
    },
    // 排序
    handleSortByColumn(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()
    },
  },
}
</script>