<template>
  <BaseContainer>
    <!-- 顶部搜索条件 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 项目类型 -->
        <el-form-item :label="$t('trials:trials-list:form:trialType')">
          <el-select v-model="searchData.trialType" style="width: 150px" clearable>
            <el-option v-for="item in $d.TrialType" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 项目编号 -->
        <el-form-item :label="$t('trials:trials-list:table:trialId')">
          <el-input v-model="searchData.TrialCode" style="width: 100px" clearable />
        </el-form-item>
        <!-- 研究方案号 -->
        <el-form-item :label="$t('trials:trials-list:table:researchNumber')">
          <el-input v-model="searchData.ResearchProgramNo" style="width: 100px" clearable />
        </el-form-item>
        <!-- 试验名称 -->
        <el-form-item :label="$t('trials:trials-list:table:experimentName')">
          <el-input v-model="searchData.ExperimentName" style="width: 100px" clearable />
        </el-form-item>

        <!-- Sponsor -->
        <el-form-item :label="$t('trials:trials-list:table:sponsor')">
          <el-input v-model="searchData.SponsorName" style="width: 100px" clearable />
        </el-form-item>

        <el-form-item>
          <!-- Search -->
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            {{ $t("common:button:search") }}
          </el-button>
          <!-- Reset -->
          <el-button type="primary" icon="el-icon-refresh-left" @click="handleReset">
            {{ $t("common:button:reset") }}
          </el-button>
          <!-- Export -->
          <!-- <el-button
            v-hasPermi="['trials:trials-list:export']"
            type="primary"
            icon="el-icon-download"
            :disabled="!(selectArr.length > 0)"
            @click="handleExportTrial"
          >
            {{ $t("common:button:export") }}
          </el-button> -->
        </el-form-item>
      </el-form>
      <span style="margin-left: auto">
        <!-- New -->
        <el-button v-hasPermi="['trials:trials-list:new']" icon="el-icon-plus" type="primary" @click="handleNew">
          {{ $t("common:button:new") }}
        </el-button>
      </span>
    </template>

    <!-- 项目列表 -->
    <template slot="main-container">
      <el-table v-adaptive="{ bottomOffset: 60 }" v-loading="listLoading" :data="list" stripe height="100"
        @sort-change="handleSortChange" @row-click="handleDetail"
        :default-sort="{ prop: 'createTime', order: 'descending' }">
        <!-- <el-table-column type="selection" align="left" width="45" /> -->
        <el-table-column width="40">
          <template slot-scope="scope">
            <i v-if="!scope.row.AuthorizationEncrypt" class="el-icon-warning-outline"
              :title="$t('trials:trials-list:tipMessage:tipOne')" style="color: red; font-size: 20px"></i>
            <i v-else-if="
              scope.row.AuthorizationEncrypt &&
              scope.row.AuthorizationDate &&
              !trialExpired(scope.row.AuthorizationDate)
            " class="el-icon-warning-outline" :title="$t('trials:trials-list:tipMessage:tipThree')"
              style="color: red; font-size: 20px"></i>
            <i v-else-if="
              scope.row.AuthorizationEncrypt &&
              scope.row.AuthorizationDate &&
              !trialExpired(scope.row.AuthorizationDate, 15)
            " class="el-icon-warning-outline" :title="$t('trials:trials-list:tipMessage:tipTwo')"
              style="color: #e6a23c; font-size: 20px"></i>
          </template>
        </el-table-column>
        <el-table-column prop="trialType" :label="$t('trials:trials-list:form:trialType')" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ $fd("TrialType", scope.row.TrialType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="TrialCode" :label="$t('trials:trials-list:table:trialId')" show-overflow-tooltip
          min-width="100" sortable="custom" />
        <el-table-column prop="ExperimentName" :label="$t('trials:trials-list:table:experimentName')"
          show-overflow-tooltip min-width="120" sortable="custom" />
        <el-table-column prop="ResearchProgramNo" :label="$t('trials:trials-list:table:researchNumber')"
          show-overflow-tooltip min-width="120" sortable="custom" />
        <el-table-column prop="Sponsor" :label="$t('trials:trials-list:table:sponsor')" min-width="90"
          show-overflow-tooltip sortable="custom" />
        <el-table-column prop="HospitalGroupName" :label="$t('trials:trials-list:table:HospitalGroupName')"
          show-overflow-tooltip min-width="120" sortable="custom" />
        <el-table-column prop="TrialStatusStr" :label="$t('trials:trials-list:table:status')" show-overflow-tooltip
          sortable="custom">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.TrialStatusStr === 'Initializing'" type="info">{{ $fd("TrialStatusEnum",
              scope.row.TrialStatusStr) }}</el-tag>
            <el-tag v-if="scope.row.TrialStatusStr === 'Ongoing'" type="primary">{{ $fd("TrialStatusEnum",
              scope.row.TrialStatusStr) }}</el-tag>
            <el-tag v-if="scope.row.TrialStatusStr === 'Completed'" type="warning">{{ $fd("TrialStatusEnum",
              scope.row.TrialStatusStr) }}</el-tag>
            <el-tag v-if="scope.row.TrialStatusStr === 'Stopped'" type="danger">{{ $fd("TrialStatusEnum",
              scope.row.TrialStatusStr) }}</el-tag>
          </template>
        </el-table-column>
        <!--阅片标准-->
        <el-table-column prop="CriterionTypeList" :label="$t('trials:trials-list:table:CriterionTypeList')"
          show-overflow-tooltip v-if="hasPermi(['role:pm', 'role:pi', 'role:sr'])" min-width="130">
          <template slot-scope="scope">
            <span>{{
              scope.row.CriterionTypeList.map((item) =>
                $fd("CriterionType", Number(item))
              ).join(",")
            }}</span>
          </template>
        </el-table-column>
        <!--待提交访视数量-->
        <el-table-column prop="UnSubmitCount" :label="$t('trials:trials-list:table:UnSubmitCount')"
          show-overflow-tooltip min-width="90" v-if="hasPermi(['role:pm'])" sortable="custom" />
        <!--待阅片数量-->
        <el-table-column prop="UnReadCount" :label="$t('trials:trials-list:table:UnReadCount')" show-overflow-tooltip
          min-width="90" v-if="hasPermi(['role:pm', 'role:pi', 'role:sr'])" sortable="custom" />
        <el-table-column prop="CreateTime" :label="$t('trials:trials-list:table:createDate')" show-overflow-tooltip
          min-width="170" sortable="custom" />
        <!--到期日-->
        <el-table-column prop="AuthorizationDate" :label="$t('trials:trials-list:table:dateAuthorized')"
          show-overflow-tooltip min-width="170" sortable="custom" />
        <!--授权时长-->
        <!-- <el-table-column
          prop="AuthorizationDuration"
          :label="$t('trials:trials-list:form:projectCycle')"
          show-overflow-tooltip
          sortable="custom"
        /> -->
        <el-table-column :label="$t('common:action:action')" min-width="200" align="left" fixed="right">
          <template slot-scope="scope">
            <!-- 详情 -->
            <el-button v-hasPermi="['trials:trials-list:panel']" circle icon="el-icon-info"
              :disabled="scope.row.IsDeleted" :title="$t('trials:trials-list:action:panel')"
              @click.stop="handleDetail(scope.row)" />
            <!-- 编辑项目基本信息 -->
            <el-button v-hasPermi="['trials:trials-list:edit']" circle icon="el-icon-edit-outline"
              :disabled="scope.row.IsDeleted" :title="$t('trials:trials-list:action:edit')"
              @click.stop="handleEdit(scope.row)" />
            <!-- 修改项目状态 -->
            <el-button v-hasPermi="['trials:trials-list:status']" circle icon="el-icon-edit"
              :disabled="scope.row.IsDeleted" :title="$t('trials:trials-list:action:status')"
              @click.stop="handleStatus(scope.row)" />
            <!-- 废除项目 -->
            <el-button v-hasPermi="['trials:trials-list:abolish']" circle icon="el-icon-delete" :disabled="scope.row.IsDeleted ||
              scope.row.TrialStatusStr !== 'Initializing'
              " :title="$t('trials:trials-list:action:abolition')" @click.stop="handleAbandon(scope.row)" />
            <!-- 激活 -->
            <el-button v-if="!scope.row.AuthorizationEncrypt" v-hasPermi="['trials:trials-list:activate']" circle
              icon="el-icon-key" :title="$t('trials:trials-list:action:activate')"
              @click.stop="handleActivate(scope.row)" />
          </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="dialogVisible" :visible.sync="dialogVisible" :title="title" :fullscreen="true" append-to-body
      custom-class="base-dialog-wrapper">
      <TrialForm :trial-id="currentId" @getList="getList" @closeDialog="closeDialog" />
    </el-dialog>

    <!-- 修改项目状态 -->
    <el-dialog v-dialogDrag v-if="statusVisible" :visible.sync="statusVisible" :close-on-click-modal="false"
      :title="$t('trials:trials-list:dialogTitle:changeStatus')" width="700px" custom-class="base-dialog-wrapper"
      append-to-body>
      <TrialStatusForm :data="currentRow" @close="closeStatusDialog" @getList="getList" />
    </el-dialog>

    <el-dialog v-if="doneDialogVisible" :visible.sync="doneDialogVisible" :title="doneTitle" :fullscreen="true"
      append-to-body custom-class="base-dialog-wrapper">
      <DoneList :trial-id="currentId" @getList="getList" @closeDialog="doneDialogVisible = false" />
    </el-dialog>
    <!--项目激活-->
    <activateProject v-if="activateVisible" :visible.sync="activateVisible" :data="currentRow" @getList="getList" />
  </BaseContainer>
</template>
<script>
import { abandonTrial, getTrialListHir } from "@/api/trials";
import { mapGetters } from "vuex";
import Excel from "exceljs";
import BaseContainer from "@/components/BaseContainer";
import Pagination from "@/components/Pagination";
import TrialForm from "./components/TrialForm";
import TrialStatusForm from "./components/TrialStatusForm";
import DoneList from "./components/DoneList";
import activateProject from "./components/activate-project.vue";
import moment from "moment";
const searchDataDefault = () => {
  return {
    Code: "",
    CriterionIds: [],
    SponsorId: "",
    ReviewTypeIds: [],
    CROId: "",
    Expedited: "",
    Indication: "",
    Phase: "",
    ModalityIds: [],
    BeginDate: "",
    EndDate: "",
    AttendedReviewerType: "",
    ResearchProgramNo: "",
    ExperimentName: "",
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: "CreateTime",
    SponsorName: "",
    trialType: null,
    TrialCode: null,
  };
};
export default {
  name: "Trials",
  components: {
    Pagination,
    BaseContainer,
    TrialForm,
    TrialStatusForm,
    DoneList,
    activateProject,
  },
  dicts: ["ReadingStandard", "ReviewType", "ReadingType"],
  data() {
    return {
      userTypeEnumInt: zzSessionStorage.getItem("userTypeEnumInt") * 1,
      doneDialogVisible: false,
      doneTitle: null,
      selectArr: [],
      searchData: searchDataDefault(),
      list: [],
      listLoading: false,
      total: 0,
      dialogVisible: false,
      title: "",
      currentId: "",
      statusVisible: false,
      currentRow: {},
      currentUser: zzSessionStorage.getItem("userName"),
      phaseOptions: [
        { value: "I" },
        { value: "II" },
        { value: "III" },
        { value: "IV" },
      ],
      expeditedOption: this.$d.TrialExpeditedState,
      beginPickerOption: {
        disabledDate: (time) => {
          if (this.searchData.EndDate) {
            return time.getTime() > new Date(this.searchData.EndDate).getTime();
          } else {
            return time.getTime() > Date.now();
          }
        },
      },
      endpickerOption: {
        disabledDate: (time) => {
          if (this.searchData.BeginDate) {
            return (
              time.getTime() > Date.now() ||
              time.getTime() <= new Date(this.searchData.BeginDate).getTime()
            );
          } else {
            return time.getTime() > Date.now();
          }
        },
      },
      // 项目激活
      activateVisible: false,
    };
  },
  computed: {
    ...mapGetters(["sponsorList", "croList"]),
  },
  created() {
    this.initPage();
  },
  mounted() {
    this.$EventBus.$on('reload', (data) => {
      window.location.reload()
    })
  },
  methods: {
    // 格式化时间
    moment(data) {
      return moment(data).format("YYYY-MM-DD");
    },
    // 项目过期判断
    trialExpired(date, isBeforeDate = 0) {
      if (
        moment(date).isBefore(
          moment().add(isBeforeDate, "day").format("YYYY-MM-DD HH:mm:ss")
        )
      ) {
        return false;
      }
      return true;
    },
    // 打开激活弹框
    async handleActivate(item) {
      this.currentRow = item;
      this.activateVisible = true;
    },
    initPage() {
      this.getList();
      // store.dispatch("global/getSponsorList");
      // store.dispatch("global/getCROList");
    },
    // 获取项目列表信息
    getList() {
      this.listLoading = true;
      getTrialListHir(this.searchData)
        .then((res) => {
          this.list = res.Result.CurrentPageData;
          this.total = res.Result.TotalCount;
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },

    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1;
      this.getList();
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault();
      this.getList();
    },
    // 新增项目
    handleNew() {
      // this.$router.push({ name: 'CreateTrial' })
      this.title = this.$t("trials:trials-list:dialogTitle:new");
      this.currentId = "";
      this.dialogVisible = true;
    },
    // 编辑项目
    handleEdit(row) {
      this.title = this.$t("trials:trials-list:dialogTitle:edit");
      this.currentId = row.Id;
      this.dialogVisible = true;
    },
    handleCommission(row) {
      this.doneTitle = this.$t("trials:trials-list:dialogTitle:doneTitle");
      this.currentId = row.Id;
      this.doneDialogVisible = true;
    },
    closeDialog() {
      this.dialogVisible = false;
    },
    // 状态
    handleStatus(row) {
      // if (row.TrialStatusStr === "Initializing") {
      //   this.listLoading = true;
      //   ifTrialCanOngoing(row.Id)
      //     .then((res) => {
      //       this.listLoading = false;
      //       if (res.Result) {
      //         this.currentRow = { ...row };
      //         this.statusVisible = true;
      //       } else {
      //         this.$confirm(res.ErrorMessage, {
      //           type: "warning",
      //           showCancelButton: false,
      //           callback: (action) => {},
      //         });
      //       }
      //     })
      //     .catch(() => {
      //       this.listLoading = false;
      //     });
      // } else {
      //   this.currentRow = { ...row };
      //   this.statusVisible = true;
      // }
      this.currentRow = { ...row };
      this.statusVisible = true;
    },
    closeStatusDialog() {
      this.statusVisible = false;
      this.activateVisible = false;
    },
    // 废除
    handleAbandon(row) {
      this.$confirm(this.$t("trials:trials-list:message:abolition"), {
        type: "warning",
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.currentRow = { ...row };
          this.abandonTrial();
        })
        .catch(() => { });
    },
    // 废除项目
    abandonTrial() {
      this.listLoading = true;
      abandonTrial(this.currentRow.Id, true)
        .then((res) => {
          this.listLoading = false;
          if (res.IsSuccess) {
            this.getList();
            this.$message.success(
              this.$t("trials:trials-list:message:abolitionSuccessfully")
            );
          }
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    // panel
    handleDetail(row) {
      this.$router.push({
        path: `/trials/trials-panel?trialId=${row.Id}&trialCode=${row.TrialCode}&researchProgramNo=${row.ResearchProgramNo}`,
      });
    },
    // 获取已勾选行数据
    handleSelectChange(val) {
      const arr = [];
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index]);
      }
      this.selectArr = arr;
    },
    // 排序
    handleSortChange(column) {
      if (column.order === "ascending") {
        this.searchData.Asc = true;
      } else {
        this.searchData.Asc = false;
      }
      if (column.prop === "Criterion") {
        this.searchData.SortField = "CriterionId";
      } else {
        this.searchData.SortField = column.prop;
      }
      this.searchData.PageIndex = 1;
      this.getList();
    },
    // 导出Excel表格
    handleExportTrial() {
      this.selectArr.forEach((element, index) => {
        // element.ExpeditedStr = element.Expedited === 0 ? 'No' : element.Expedited === 1 ? '24H' : '48H'
        // element.ModalityListStr = element.ModalityList.join(', ')
        // element.CreateTimeStr = element.CreateTime
        // element.Criterion = element.CriterionList.join(', ')
        element.Deleted = element.IsDeleted ? "Yes" : "No";
        element.Index = index + 1;
      });
      var workbook = new Excel.Workbook();
      var sheet = workbook.addWorksheet("Trials");

      sheet.properties.defaultRowHeight = 22;
      // sheet.columns = [
      //   { key: 'Index', width: 5 },
      //   { key: 'Code', width: 15 },
      //   { key: 'ExpeditedStr', width: 13 },
      //   { key: 'TrialStatusStr', width: 10 },
      //   { key: 'Indication', width: 25 },
      //   { key: 'Phase', width: 10 },
      //   { key: 'ReviewType', width: 20 },
      //   { key: 'Criterion', width: 15 },
      //   { key: 'ModalityListStr', width: 30 },
      //   { key: 'CRO', width: 10 },
      //   { key: 'Sponsor', width: 20 },
      //   { key: 'CreateTimeStr', width: 18 }
      // ]
      sheet.columns = [
        { key: "Index", width: 5 },
        { key: "TrialCode", width: 25 },
        { key: "ExperimentName", width: 25 },
        { key: "ResearchProgramNo", width: 25 },
        { key: "Sponsor", width: 25 },
        { key: "Deleted", width: 10 },
        { key: "CreateTime", width: 25 },
      ];

      // 处理标题
      sheet.mergeCells("A1", "G2");
      sheet.getCell("A1").value = "Trials";
      sheet.getCell("A1").alignment = {
        vertical: "middle",
        horizontal: "center",
      };
      sheet.getCell("A1").font = {
        name: "SimSun",
        family: 4,
        size: 13,
        bold: true,
      };
      sheet.mergeCells("A3", "G3");
      var now = new Date();
      sheet.getCell("A3").value = now.toLocaleDateString();
      sheet.getCell("A3").alignment = {
        vertical: "middle",
        horizontal: "right",
      };

      sheet.getRow(4).values = [
        "NO.",
        "Trial ID",
        "试验名称",
        "研究方案号",
        "申办方",
        "是否废除",
        "Date Created",
      ];
      sheet.getRow(4).font = {
        name: "SimSun",
        family: 4,
        size: 11,
        bold: true,
      };
      sheet.getRow(4).alignment = { vertical: "middle", horizontal: "left" };

      sheet.addRows(this.selectArr);

      sheet.eachRow((row, number) => {
        if (number > 3) {
          row.eachCell((cell, rowNumber) => {
            cell.alignment = { vertical: "center", horizontal: "left" };
            cell.border = {
              top: { style: "thin" },
              left: { style: "thin" },
              bottom: { style: "thin" },
              right: { style: "thin" },
            };
          });
        }
      });

      workbook.xlsx
        .writeBuffer({
          base64: true,
        })
        .then(function (xls64) {
          var data = new Blob([xls64], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });

          if ("msSaveOrOpenBlob" in navigator) {
            // ie使用的下载方式
            window.navigator.msSaveOrOpenBlob(data, "Trials" + ".xlsx");
          } else {
            var a = document.createElement("a");

            var url = URL.createObjectURL(data);
            a.href = url;
            a.download = "Trials" + ".xlsx";
            document.body.appendChild(a);
            a.click();
            setTimeout(function () {
              document.body.removeChild(a);
              window.URL.revokeObjectURL(url);
            }, 0);
          }
        });
    },
  },
};
</script>
