<template>
  <div class="app-container trials-data data-list">
    <div class="filter-container">
      <el-input
        v-model="listQuery.KeyWord"
        size="small"
        placeholder="Trial ID or Indication"
        style="width:170px;margin-right:5px;"
      />
      <el-select v-if="croList" v-model="listQuery.CroId" size="small" style="width:130px;" placeholder="CRO" clearable class="interval">
        <el-option
          v-for="(item) of croList"
          :key="item.Id"
          :label="item.CROName"
          :value="item.Id"
        />
      </el-select>
      <el-button size="small" type="text" @click="handleReset">Reset</el-button>
      <el-button type="primary" size="small" @click="handleSearch">Search</el-button>
    </div>
    <div class="list-container">
      <el-table
        v-loading="listLoading"
        height="100%"
        :data="list"
        stripe
        class="table"
        size="small"
        @sort-change="sortByColumn"
      >
        <el-table-column type="index" width="40" />
        <el-table-column
          prop="TrialCode"
          label="Trial ID"
          show-overflow-tooltip
          min-width="100"
          sortable="custom"
        />
        <el-table-column
          prop="Indication"
          label="Indication"
          show-overflow-tooltip
          min-width="110"
          sortable="custom"
        />
        <el-table-column
          prop="Cro"
          sortable="custom"
          label="CRO"
          min-width="80"
          show-overflow-tooltip
        />
        <el-table-column
          prop="Expedited"
          label="Expedited"
          show-overflow-tooltip
          min-width="110"
          sortable="custom"
        >
          <template slot-scope="scope">{{ scope.row.Expedited == 0?'No':scope.row.Expedited == 1?'24-Hour':'48-Hour' }}</template>
        </el-table-column>
        <el-table-column
          prop="TrialAdditional"
          label="Project Adjustment ($)"
          show-overflow-tooltip
          min-width="180"
          sortable="custom"
        />
        <el-table-column
          prop="AdjustmentMultiple"
          label="Adjustment Multiple"
          show-overflow-tooltip
          min-width="150"
        />
        <el-table-column
          prop="IsNewTrial"
          label="IsNewTrial"
          show-overflow-tooltip
          min-width="80"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.IsNewTrial"
              :active-value="true"
              :inactive-value="false"
              @change="(event) => {return switchChange(event, scope.row)}"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="Reviewers"
          label="Reviewers"
          show-overflow-tooltip
          min-width="150"
        >
          <template slot-scope="scope">
            <el-popover v-model="scope.row.isPopover" :width="1200" trigger="manual" placement="bottom">
              <trials-data-reviewers ref="TrialsDataReviewers" :doctor-list="doctorList" @getList="getTrialDoctorList" />
              <div style="text-align: right; margin: 0; margin-top: 10px;">
                <el-button type="primary" size="small" @click="$set(scope.row, 'isPopover', false)">close</el-button>
              </div>
              <div slot="reference" class="name-wrapper">
                <el-tag v-if="scope.row.DoctorsNames" style="cursor: pointer" size="medium" @click="getTrialDoctorList(scope.row)">{{ scope.row.DoctorsNames }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column
          label="Statement of Work"
          min-width="150"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <div v-if="scope.row.SowPath">
              <el-button size="small" type="text" style="margin-right:10px;" @click="handleView(scope.row)">View</el-button>
              <el-button size="small" type="text" @click="handleDeleteSOW(scope.row)">Delete</el-button>
            </div>
            <div v-else>
              <el-button
                size="small"
                type="text"
                style="margin-left:10px;"
                @click="handleUpload(scope.row)"
              >Upload</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="CreateTime"
          label="Date Created"
          min-width="130"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          label="Action"
          min-width="200"
        >
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              @click="handleEdit(scope.row)"
            >Edit</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <pagination :total="total" :page.sync="listQuery.PageIndex" :limit.sync="listQuery.PageSize" @pagination="getList" />
    </div>
    <el-dialog
      :key="trialForm.DoctorId"
      title="Edit"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      size="small"
    >
      <el-form ref="trialsData" :model="trialForm" size="small" label-width="170px" :rules="rules">
        <el-form-item label="Project ID">
          <el-input v-model="trialForm.TrialCode" readonly />
        </el-form-item>
        <el-form-item label="Indication">
          <el-input v-model="trialForm.Indication" readonly />
        </el-form-item>
        <el-form-item label="Expedited">
          <el-input v-model="trialForm.Expedited" readonly />
        </el-form-item>
        <el-form-item label="IsNewTrial">
          <el-switch
            v-model="trialForm.IsNewTrial"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
        <el-form-item label="Project Adjustment ($)" prop="TrialAdditional">
          <el-input v-model="trialForm.TrialAdditional" placeholder="Trial Additional" type="number" oninput="value= value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')" />
        </el-form-item>
        <el-form-item label="Adjustment Multiple" prop="AdjustmentMultiple">
          <el-input v-model="trialForm.AdjustmentMultiple" placeholder="Multiple" type="number" oninput="value= value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" :disabled="btnDisabled" size="small" @click="handleSave">Ok</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :key="trialId"
      title="Signed Statement of Work"
      :visible.sync="sowDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <upload-sow ref="uploadSow" :trial-id="trialId" @getFileList="getFileList" />
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import UploadSow from './UploadSow'
import TrialsDataReviewers from './TrialsDataReviewers'
import { getTrialPaymentPriceList, addOrUpdateTrialPaymentPrice, deleteTrialSOW, getTrialDoctorList } from '@/api/financials'
import { formatUTCTime } from '@/utils/formatter'
import store from '@/store'
import { mapGetters } from 'vuex'
const regx = /^([1-9]\d*(\.\d+)?|0)$/
const getListQueryDefault = () => {
  return {
    KeyWord: '',
    // CroId: '',
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: ''
  }
}
export default {
  name: 'TrialsData',
  components: { Pagination, UploadSow, TrialsDataReviewers },
  data() {
    return {
      listQuery: getListQueryDefault(),
      list: [],
      doctorList: [],
      total: 0,
      isPopover: false,
      listLoading: false,
      trialForm: {},
      dialogVisible: false,
      btnDisabled: false,
      trialId: '',
      sowDialogVisible: false,
      currentRow: {},
      Expedited: 0,
      rules: {
        TrialAdditional: [
          { required: true, trigger: 'blur' },
          { pattern: regx, message: 'Please specify a number' }
        ],
        AdjustmentMultiple: [
          { required: true, trigger: 'blur' },
          { pattern: regx, message: 'Please specify a number' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['croList'])
  },
  mounted() {
    store.dispatch('global/getCROList')
    this.getList()
  },
  methods: {
    switchChange(event, item) {
      this.listLoading = true
      addOrUpdateTrialPaymentPrice(item).then(res => {
        this.$message.success('Saved successfully!')
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    getTrialDoctorList(row, is) {
      if (!is) {
        this.list.forEach(v => {
          this.$set(v, 'isPopover', false)
        })
      }
      this.listLoading = true
      var params = {
        Asc: true,
        SortField: 'string',
        TrialId: row.TrialId,
        PageIndex: 1,
        PageSize: 500
      }
      getTrialDoctorList(params).then(res => {
        this.doctorList = res.Result.CurrentPageData
        this.doctorList.forEach(v => {
          this.list.forEach(j => {
            if (j.TrialId === row.TrialId) {
              this.$set(v, 'Expedited', j.Expedited)
              this.$set(v, 'ReviewMode', j.ReviewMode)
            }
          })
        })
        this.$set(row, 'isPopover', true)
        this.listLoading = false
      }).catch(() => { this.listLoading = false })
    },
    getList() {
      this.listLoading = true
      getTrialPaymentPriceList(this.listQuery).then(res => {
        this.listLoading = false
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
      }).catch(() => { this.listLoading = false })
    },
    handleEdit(row) {
      this.trialForm = (({ TrialId, TrialCode, Indication, TrialAdditional, AdjustmentMultiple, IsNewTrial }) => ({ TrialId, TrialCode, Indication, TrialAdditional, AdjustmentMultiple, IsNewTrial }))(row)
      this.trialForm.Expedited = row.Expedited === 0 ? 'No' : row.Expedited === 1 ? '24-Hour' : '48-Hour'
      this.dialogVisible = true
    },
    handleSave() {
      this.$refs.trialsData.validate(valid => {
        if (valid) {
          this.btnDisabled = true

          addOrUpdateTrialPaymentPrice(this.trialForm).then(res => {
            this.btnDisabled = false
            this.dialogVisible = false
            this.getList()
            this.$message.success('Updated successfully')
          }).catch(() => { this.btnDisabled = false })
        }
      })
    },
    handleSearch() {
      this.listQuery.PageIndex = 1
      this.getList()
    },
    handleReset() {
      Object.assign(this.listQuery, getListQueryDefault())
      this.getList()
    },
    handleUpload(row) {
      this.currentRow = row
      this.trialId = row.TrialId
      this.sowDialogVisible = true
      let fileList = []
      if (row.SowName) {
        fileList = [{ name: row.SowName, FileName: row.SowName, Path: row.SowPath, FullPath: row.SowFullPath, Type: 'Statement of Work' }]
      }
      this.$nextTick(function() {
        this.$refs.uploadSow.initFileList(fileList)
      })
    },
    handleView(row) { row.SowFullPath ? window.open(row.SowFullPath, '_blank') : '' },
    handleDeleteSOW(row) {
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,

      })
        .then(() => {
          const param = { SowPath: row.SowPath, TrialId: row.TrialId }
          deleteTrialSOW(param)
            .then(res => {
              row.SowPath = ''
              row.SowName = ''
              row.SowFullPath = ''
              this.$message.success('Deleted successfully !')
            })
        })
        .catch(action => {})
    },
    getFileList(fileList) {
      this.currentRow.SowPath = fileList.length > 0 ? fileList[0].Path : ''
      this.currentRow.SowName = fileList.length > 0 ? fileList[0].FileName : ''
      this.currentRow.SowFullPath = fileList.length > 0 ? fileList[0].FullPath : ''
    },
    sortByColumn(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()
    },
    timeFormatter(row) {
      if (row.CreateTime) {
        return formatUTCTime(row.CreateTime)
      }
    }
  }

}
</script>
<style lang="scss" scoped>
.trials-data{
  padding: 0;
  .list-container{
    height: calc(100% - 70px);
  }
}
</style>
