<template>
  <box-content>
    <div class="search">
      <el-form :inline="true" class="base-search-form">
        <!-- 是否需要回执 -->
        <el-form-item :label="$t('trials:emailManageCfg:title:isReturnRequired')" v-if="!systemLevel">
          <el-select v-model="searchData.IsReturnRequired" clearable style="width: 100px">
            <el-option v-for="item of $d.YesOrNo" :value="item.value" :label="item.label" :key="item.id" />
          </el-select>
        </el-form-item>
        <!-- 是否加急 -->
        <!-- <el-form-item :label="$t('dictionary:email:label:IsUrgent')" v-if="!systemLevel">
          <el-select v-model="searchData.IsUrgent" clearable style="width: 100px">
            <el-option v-for="item of $d.YesOrNo" :value="item.value" :label="item.label" :key="item.id" />
          </el-select>
        </el-form-item> -->
        <!-- 是否启用 -->
        <el-form-item :label="$t('trials:emailManageCfg:table:IsEnable')" v-if="!systemLevel">
          <el-select v-model="searchData.IsEnable" clearable style="width: 100px">
            <el-option v-for="item of $d.YesOrNo" :value="item.value" :label="item.label" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:auditRecord:table:criterion')" v-if="isDistinguishCriteria && !systemLevel">
          <el-select v-model="searchData.CriterionTypeEnum" clearable style="width: 100px">
            <el-option v-for="item of $d.CriterionType" :value="item.value" :label="item.label" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:emailManageCfg:form:BusinessModule')">
          <el-select v-model="searchData.BusinessModuleEnum" clearable style="width: 100px">
            <el-option v-for="item of $d.BusinessModule" :value="item.value" :label="item.label" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:emailManageCfg:form:BusinessScenario')">
          <el-select v-model="searchData.BusinessScenarioEnum" clearable style="width: 100px">
            <el-option v-for="item of $d.Email_BusinessScenario" :value="item.value" :label="item.label"
              :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:emailManageCfg:form:ToUserType')">
          <el-select v-model="searchData.ToUserType" clearable style="width: 100px">
            <el-option v-for="item of UserTypeList" :value="item.value" :label="item.label" :key="item.id" />
          </el-select>
        </el-form-item>
        <!--v-if="systemLevel === 1"-->
        <el-form-item :label="$t('trials:emailManageCfg:form:EmailUrgent')">
          <el-select v-model="searchData.EmailUrgentEnum" clearable style="width: 100px">
            <el-option v-for="item of $d.EmailUrgent" :value="item.value" :label="item.label" :key="item.id" />
          </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-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleExport">
            {{ $t('common:button:export') }}
          </el-button>
          <!-- <el-button
      type="primary"
      size="mini"
    >
      场景配置
    </el-button> -->
          <el-button type="primary" @click="handleAdd">
            {{ $t('common:button:new') }}
          </el-button>
          <el-button type="primary" @click="openDrawer" :disabled="multipleSelection.length <= 0">
            {{ $t('trials:emailManageCfg:button:batchAudit') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 受试者列表 -->
    <el-table v-loading="loading" v-adaptive="{ bottomOffset: 45 }" :data="list" stripe height="100" style="width: 100%"
      @sort-change="handleSortByColumn" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="index" width="40" /> -->
      <el-table-column type="selection" width="55">
      </el-table-column>
      <!-- Code -->
      <el-table-column prop="Code" :label="$t('trials:emailManageCfg:title:code')" sortable="custom"
        show-overflow-tooltip min-width="100" />
      <el-table-column v-if="isDistinguishCriteria" prop="TrialReadingCriterionId"
        :label="$t('trials:reviewTrack:table:criterionName')" show-overflow-tooltip sortable="custom" min-width="120">
        <template slot-scope="scope">
          {{scope.row.CriterionTypeList ? scope.row.CriterionTypeList.map(item => $fd('CriterionType', item)).join(', ')
            : ''}}
        </template>
      </el-table-column>
      <!-- 邮件主题（中文） -->
      <el-table-column prop="EmailTopicCN" :label="$t('trials:emailManageCfg:table:EmailTopicCN')" sortable="custom"
        show-overflow-tooltip min-width="160" />
      <!-- 邮件主题（英文） -->
      <el-table-column prop="EmailTopic" :label="$t('trials:emailManageCfg:table:EmailTopic')" sortable="custom"
        show-overflow-tooltip min-width="160" />
      <!-- 业务层级 -->
      <el-table-column prop="BusinessLevelEnum" :label="$t('dictionary:email:label:businessLevel')" sortable="custom"
        show-overflow-tooltip min-width="150">
        <template slot-scope="scope">
          {{ $fd('BusinessLevel', scope.row.BusinessLevelEnum) }}
        </template>
      </el-table-column>
      <!-- 业务模块 -->
      <el-table-column prop="BusinessModuleEnum" :label="$t('dictionary:email:label:businessModule')" sortable="custom"
        show-overflow-tooltip min-width="160">
        <template slot-scope="scope">
          {{ $fd('BusinessModule', scope.row.BusinessModuleEnum) }}
        </template>
      </el-table-column>
      <!-- 业务场景 -->
      <el-table-column prop="BusinessScenarioEnum" :label="$t('trials:emailManageCfg:table:BusinessScenarioEnum')"
        sortable="custom" show-overflow-tooltip min-width="130">
        <template slot-scope="scope">
          {{ $fd('Email_BusinessScenario', scope.row.BusinessScenarioEnum) }}
        </template>
      </el-table-column>
      <!-- 收件人v-if="systemLevel !== 1" -->
      <el-table-column prop="ToUserTypeList" :label="$t('trials:emailManageCfg:title:toUserTypeList')"
        show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          {{
            scope.row.ToUserTypeList.length > 0
              ? scope.row.ToUserTypeList.map((v) => $fd('UserType', v)).join(
                '、'
              )
              : ''
          }}
        </template>
      </el-table-column>
      <!-- 抄送人v-if="!systemLevel" -->
      <el-table-column prop="CopyUserTypeList" :label="$t('trials:emailManageCfg:title:copyUserTypeList')"
        show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          {{
            scope.row.CopyUserTypeList.length > 0
              ? scope.row.CopyUserTypeList.map((v) => $fd('UserType', v)).join(
                '、'
              )
              : ''
          }}
        </template>
      </el-table-column>
      <!-- 加急状态 -->
      <el-table-column prop="EmailUrgentEnum" :label="$t('dictionary:email:label:IsUrgent')" sortable="custom"
        show-overflow-tooltip min-width="110">
        <template slot-scope="scope">
          {{ $fd('EmailUrgent', scope.row.EmailUrgentEnum) }}
        </template>
      </el-table-column>
      <!-- 发送周期和时间 -->
      <el-table-column prop="EmailCron" :label="$t('trials:emailManageCfg:table:EmailCron')" sortable="custom"
        show-overflow-tooltip min-width="180" />
      <!-- 附件 -->
      <el-table-column prop="FileName" :label="$t('trials:emailManageCfg:title:fileName')" show-overflow-tooltip
        min-width="100" v-if="!systemLevel">
        <template slot-scope="scope">
          <el-button v-if="scope.row.FilePath" type="text" @click="handlePreview(scope.row.FilePath)">
            {{ scope.row.FileName }}
          </el-button>
        </template>
      </el-table-column>
      <!-- 是否需要回执 -->
      <el-table-column prop="IsReturnRequired" :label="$t('trials:emailManageCfg:title:isReturnRequired')"
        show-overflow-tooltip sortable="custom" min-width="160" v-if="!systemLevel">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsReturnRequired" type="danger">
            {{ $fd('YesOrNo', scope.row.IsReturnRequired) }}
          </el-tag>
          <el-tag v-else type="primary">{{
            $fd('YesOrNo', scope.row.IsReturnRequired)
          }}</el-tag>
        </template>
      </el-table-column>
      <!-- 是否自动发送 -->
      <el-table-column prop="IsAutoSend" :label="$t('trials:emailManageCfg:title:isAutoSend')" show-overflow-tooltip
        sortable="custom" min-width="160" v-if="!systemLevel">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsAutoSend" type="danger">
            {{ $fd('YesOrNo', scope.row.IsAutoSend) }}
          </el-tag>
          <el-tag v-else type="primary">{{
            $fd('YesOrNo', scope.row.IsAutoSend)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="IsEnable" :label="$t('trials:emailManageCfg:table:IsEnable')" show-overflow-tooltip
        sortable="custom" min-width="160" v-if="!systemLevel">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.IsEnable" type="danger">
            {{ $fd('YesOrNo', scope.row.IsEnable) }}
          </el-tag>
          <el-tag v-else type="primary">{{
            $fd('YesOrNo', scope.row.IsEnable)
          }}</el-tag>
        </template>
      </el-table-column>
      <!-- 更新时间 -->
      <el-table-column prop="UpdateTime" :label="$t('trials:emailManageCfg:title:updateTime')" show-overflow-tooltip
        sortable="custom" min-width="160" />
      <!-- 创建时间 -->
      <el-table-column prop="CreateTime" :label="$t('trials:emailManageCfg:title:createTime')" show-overflow-tooltip
        sortable="custom" min-width="160" />
      <el-table-column :label="$t('common:action:action')" min-width="180" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">
            {{ $t('common:button:edit') }}
          </el-button>

          <el-button type="text" @click="handleDelete(scope.row)">
            {{ $t('common:button:delete') }}
          </el-button>
          <el-button type="text" @click="
            preview(scope.row.EmailHtmlContentCN, scope.row.EmailHtmlContent)
            ">{{ $t('common:button:preview') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
      @pagination="getList" />
    <!-- 搜索框 -->
    <!-- 修改受试者状态 -->
    <el-dialog v-if="editVisible" :visible.sync="editVisible" :close-on-click-modal="false" :title="title" width="700px"
      fullscreen custom-class="base-dialog-wrapper">
      <EmailForm :data="rowData" :system-level="systemLevel" :isDistinguishCriteria="isDistinguishCriteria"
        @closeDialog="closeDialog" @getList="getList" @PreviewHTML="preview" />
    </el-dialog>

    <!-- 修改受试者状态 -->
    <el-dialog v-if="attachmentVisible" :visible.sync="attachmentVisible" :close-on-click-modal="false"
      :title="$t('trials:emailManageCfg:title:fileName')" width="80%" custom-class="base-dialog-wrapper" append-to-body>
      <AttachmentList :business-scenario-enum="rowData.BusinessScenarioEnum"
        :is-distinguish-criteria="rowData.IsDistinguishCriteria" @getList="getList" />
    </el-dialog>
    <!-- 预览模板 -->
    <el-dialog v-if="previewVisible" :visible.sync="previewVisible" :close-on-click-modal="false"
      :title="$t('common:button:preview')" fullscreen custom-class="base-dialog-wrapper">
      <div style="
          display: flex;
          align-items: flex-start;
          justify-content: space-around;
          flex-wrap: wrap;
        ">
        <div style="min-width: 50%">
          <!-- 邮件内容模版（CN） -->
          <h3>{{ $t('dictionary:email:title:title1') }}</h3>
          <div v-html="previewHTML"></div>
        </div>
        <div style="min-width: 50%">
          <!-- 邮件内容模版（EN） -->
          <h3>{{ $t('dictionary:email:title:title2') }}</h3>
          <div v-html="previewHTMLEN"></div>
        </div>
      </div>
    </el-dialog>
    <el-drawer :title="$t('trials:emailManageCfg:title:audit')" :visible.sync="drawer" direction="rtl" size="80%">
      <!-- <div style="width: 800px">
        <el-form label-width="100px" @submit.native.prevent size="small" :inline="true" class="demo-form-inline">
          <el-form-item :label="$t('il8n:search:keyword')">
            <el-input v-model="key" @input="keyChange" />
          </el-form-item>
          <el-form-item :label="$t('il8n:search:state')">
            <el-select v-model="State" clearable filterable @change="handleStateChange">
              <el-option v-for="item of $d.InternationalizationKeyState"
                :key="'InternationalizationKeyState' + item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </div> -->
      <el-table :data="tableData" v-adaptive="{ bottomOffset: 50 }" height="100" style="width: 100%"
        @sort-change="handleSortByColumnDrawer">
        <!-- Code -->
        <el-table-column prop="Code" :label="$t('trials:emailManageCfg:title:code')" sortable="custom"
          show-overflow-tooltip min-width="100" />
        <el-table-column v-if="isDistinguishCriteria" prop="TrialReadingCriterionId"
          :label="$t('trials:reviewTrack:table:criterionName')" show-overflow-tooltip sortable="custom" min-width="120">
          <template slot-scope="scope">
            {{ $fd('CriterionType', scope.row.CriterionTypeEnum) }}
          </template>
        </el-table-column>
        <!-- 邮件主题（中文） -->
        <el-table-column prop="EmailTopicCN" :label="$t('trials:emailManageCfg:table:EmailTopicCN')" sortable="custom"
          show-overflow-tooltip min-width="160">
          <template slot-scope="scope">
            <el-input v-model="scope.row.EmailTopicCN" @input="
              (e) => {
                $set(scope.row, 'EmailTopicCN', e)
              }
            " size="mini"></el-input>
          </template>
        </el-table-column>
        <!-- 邮件主题（英文） -->
        <el-table-column prop="EmailTopic" :label="$t('trials:emailManageCfg:table:EmailTopic')" sortable="custom"
          show-overflow-tooltip min-width="160">
          <template slot-scope="scope">
            <el-input v-model="scope.row.EmailTopic" @input="
              (e) => {
                $set(scope.row, 'EmailTopic', e)
              }
            " size="mini"></el-input>
          </template>
        </el-table-column>
        <!-- 业务层级 -->
        <el-table-column prop="BusinessLevelEnum" :label="$t('dictionary:email:label:businessLevel')" sortable="custom"
          show-overflow-tooltip min-width="150">
          <template slot-scope="scope">
            {{ $fd('BusinessLevel', scope.row.BusinessLevelEnum) }}
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; padding-top: 10px; padding-right: 10px">
        <el-button size="mini" @click="drawer = false">{{ $t('common:button:cancel') }}
        </el-button>
        <el-button size="mini" type="primary" @click="handleSave">{{
          $t('common:button:save')
        }}</el-button>
      </div>
    </el-drawer>
  </box-content>
</template>
<script>
import {
  getEmailNoticeConfigList,
  deleteEmailNoticeConfig,
  batchUpdateEmail
} from '@/api/dictionary'
import { GetEmailNoticeConfigList_Export } from '@/api/export'
import BoxContent from '@/components/BoxContent'
import Pagination from '@/components/Pagination'
import EmailForm from './EmailForm'
import AttachmentList from './AttachmentList'
const searchDataDefault = () => {
  return {
    IsReturnRequired: '',
    IsUrgent: '',
    IsEnable: '',
    CriterionTypeEnum: null,
    BusinessModuleEnum: null,
    BusinessScenarioEnum: null,
    EmailUrgentEnum: null,
    ToUserType: null,
    PageIndex: 1,
    PageSize: 20,
    SortField: 'Code',
    Asc: true,
  }
}
export default {
  name: 'EmailList',
  components: { BoxContent, Pagination, EmailForm, AttachmentList },
  props: {
    isDistinguishCriteria: {
      type: Boolean,
      default() {
        return false
      },
    },
    systemLevel: {
      type: Number,
      default() {
        return 0
      },
    },
  },
  data() {
    return {
      activeTab: '0',
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      rowData: {},
      title: '',
      editVisible: false,
      attachmentVisible: false,
      previewVisible: false,
      previewHTML: null,
      previewHTMLEN: null,
      multipleSelection: [],
      drawer: false,
      tableData: []
    }
  },
  computed: {
    UserTypeList() {
      if (this.systemLevel === 1) {
        return this.$d.UserType
      } else {
        return this.$d.UserType.filter(
          (item) => ![7, 31, 32, 21, 26, 27].includes(item.value)
        )
      }
    },
  },
  mounted() {
    this.getList()
  },
  methods: {
    async handleSave() {
      try {
        let arr = []
        this.tableData.forEach(item => {
          let obj = {
            EmailTopic: item.EmailTopic,
            EmailTopicCN: item.EmailTopicCN,
            Id: item.Id
          }
          arr.push(obj)
        })
        this.drawer = false
        let res = await batchUpdateEmail(arr)
        if (res.IsSuccess) {
          this.$message.success(this.$t('trials:emailManageCfg:message:auditSuccess'))
          this.getList()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 排序
    handleSortByColumnDrawer(column) {
      if (column.order === 'ascending') {
        this.tableData.sort((a, b) =>
          a[column.prop].localeCompare(b[column.prop])
        )
      } else {
        this.tableData.sort((a, b) =>
          b[column.prop].localeCompare(a[column.prop])
        )
      }
    },
    openDrawer() {
      this.tableData = []
      this.multipleSelection.forEach(item => {
        let obj = Object.assign({}, item)
        this.tableData.push(obj)
      })
      this.drawer = true
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 获取受试者列表
    getList() {
      this.loading = true
      this.searchData.IsDistinguishCriteria = this.isDistinguishCriteria
      this.searchData.systemLevel = this.systemLevel
      getEmailNoticeConfigList(this.searchData)
        .then((res) => {
          this.loading = false
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 新增
    handleAdd() {
      this.rowData = {}
      this.title = this.$t('common:button:new')
      this.editVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.rowData = { ...row }
      this.title = this.$t('common:button:edit')
      this.editVisible = true
    },
    // 删除
    handleDelete(row) {
      this.$confirm(this.$t('trials:staffResearch:message:confirmDel'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        deleteEmailNoticeConfig(row.Id).then((res) => {
          if (res.IsSuccess) {
            this.getList()
            this.$message.success(this.$t('common:message:deletedSuccessfully'))
          }
        })
      })
    },
    handleDetail(row) {
      this.rowData = { ...row }
      this.attachmentVisible = true
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      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()
    },
    // 关闭新增、编辑框
    closeDialog() {
      this.editVisible = false
    },
    preview(html, htmlEN) {
      this.previewHTML = html
      this.previewHTMLEN = htmlEN
      this.previewVisible = true
    },
    // 导出
    handleExport() {
      // this.searchData.IsDistinguishCriteria = this.isDistinguishCriteria
      // this.searchData.systemLevel = this.systemLevel
      // return GetEmailNoticeConfigList_Export(this.searchData)
      return GetEmailNoticeConfigList_Export(this.searchData)
    },
  },
}
</script>
<style lang="scss" scoped>
.box-body .search .base-search-form .el-form-item {
  margin-bottom: 10px;
}
</style>
