<template>
  <div class="sendRecord">
    <el-card shadow="never" style="margin-bottom:20px;">
      <el-form v-model="pagerDto" inline>
        <el-form-item label="发送状态">
          <el-select v-model="pagerDto._Eq_ExecuteState" placeholder="发送状态" clearable filterable>
            <el-option v-for="item in executeStateOptions" :key="item.Id" :label="item.Name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮件类型">
          <el-select v-model="pagerDto._Eq_MailType" placeholder="邮件类型" clearable filterable>
            <el-option v-for="item in mailTypeOptions" :key="item.Id" :label="item.Name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item label="提单号">
          <el-input v-model="pagerDto._Eq_LadingBillNumber" clearable />
        </el-form-item>
        <el-form-item label="订单号">
          <el-tooltip v-model="openNumbersInput" effect="light" :manual="true">
            <div slot="content">
              <el-input v-model="inputMultiCodes" type="textarea" rows="7" placeholder="请输入单号，每行一个" />
              <div style="text-align: right; padding: 5px">
                <el-button size="mini" @click="openNumbersInput = false">关闭</el-button>
                <el-button size="mini" type="danger" @click="inputMultiCodes = ''">清除</el-button>
                <el-button size="mini" type="success" @click="confirmMultiCodes">确定</el-button>
              </div>
            </div>
            <el-input v-model="pagerDto._In_Number" clearable @focus="openNumbersInputPannel" />
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="tableLoading" @click="serarch()">查询</el-button>
          <!-- <el-button type="success" @click="addEditMailRecord()">新增</el-button> -->
          <el-button
            type="warning"
            :loading="tableLoading"
            @click="hanleResend()"
            v-if="pagerDto._Eq_ExecuteState==4"
          >选择重新发送</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never" style="margin-bottom:20px;">
      <el-table
        border
        :data="dataSource"
        :highlight-current-row="true"
        :select-on-indeterminate="true"
        :height="570"
        :loading="tableLoading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="Id" type="selection" />
        <el-table-column label="系统单号" prop="SystemNo" :min-width="130" />
        <el-table-column label="跟踪单号" prop="TrackingNumber" :min-width="130" />
         <el-table-column label="提单号" prop="LadingBillNumber" :min-width="130" />
        <el-table-column label="收件人姓名" prop="ReceiverName" :min-width="110" />
        <el-table-column label="收件人邮箱地址" prop="ReceiverEmail" :min-width="120" />
        <el-table-column label="预计发送时间" prop="EstimatedTime" :min-width="120" />
        <el-table-column label="执行时间" prop="ActualTime" :min-width="100" />
        <el-table-column label="记录执行次数" prop="ExecutionTimes" :min-width="110" />
        <el-table-column label="发送状态" prop="ExecuteState" :min-width="90">
          <template slot-scope="scope">
            <div v-if="scope.$index >= 0">
              {{ getExecuteState(scope.row.ExecuteState) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="结果信息" prop="ResultMsg" :min-width="130" :show-overflow-tooltip="true" />
        <el-table-column label="邮件类型" prop="MailType" :min-width="100">
          <template slot-scope="scope">
            <div v-if="scope.$index >= 0">
              {{ getMailType(scope.row.MailType) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="模版名称" prop="MailTemplateName" :min-width="100" />
        <el-table-column label="操作" fixed="right" :width="90">
          <template slot-scope="scope">
            <el-button v-if="scope.row.ExecuteState!=3" type="primary" size="mini" @click="addEditMailRecord(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[20, 50, 100, 150, 200]"
        :current-page="pagerDto.PageIndex"
        :page-size="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @current-change="pagerSerach"
        @size-change="sizeChange"
      />
    </el-card>
    <!-- 新增或修改模版 -->
    <el-dialog
      :title="getRecordTitle"
      :visible.sync="dialogTemplate"
      width="42%"
      :before-close="handleCloseRecord"
      custom-class="record-form"
    >
      <el-form ref="recordFormRef" :model="recordParamsDto" label-width="120px" :rules="templateParamsRules" inline>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收件人姓名" prop="ReceiverName">
              <el-input v-model="recordParamsDto.ReceiverName" placeholder="收件人姓名" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人邮箱地址" prop="ReceiverEmail">
              <el-input v-model="recordParamsDto.ReceiverEmail" placeholder="收件人邮箱地址" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计发送时间" prop="EstimatedTime">
              <el-date-picker
                v-model="recordParamsDto.EstimatedTime"
                class="estimated-time"
                type="date"
                value-format="yyyy-MM-ddTHH:mm:ss"
                placeholder="预计发送时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件类型" prop="MailType">
              <el-select v-model="recordParamsDto.MailType" placeholder="邮件类型" clearable filterable>
                <el-option v-for="item in mailTypeOptions" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件模版" prop="MailTemplateId">
              <el-select v-model="recordParamsDto.MailTemplateId" placeholder="邮件模版" clearable filterable>
                <el-option v-for="item in mailTypeOptions" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发送状态" prop="ExecuteState">
              <el-select v-model="recordParamsDto.ExecuteState" placeholder="发送状态" clearable filterable>
                <el-option v-for="item in executeStateOptions" :key="item.Id" :label="item.Name" :value="item.Id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseRecord">取 消</el-button>
        <el-button type="primary" @click="hanleSubmitTemplate">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getEnumsGetDes } from '@/api/enum/enums'
import { _queryMailRecordPage, _retrySend, _saveMailRecord, _getAllMailTemplates } from '@/api/email'
import { format } from '@/utils/multiInput'

export default {
  name: 'SendRecord',
  data() {
    return {
      pagerDto: {
        _Eq_ExecuteState: undefined,
        _Eq_MailType: undefined,
        _Eq_LadingBillNumber: '',
        _In_Number: undefined,
        PageIndex: 1,
        PageSize: 20,
        total: 0
      },
      inputMultiCodes: '',
      openNumbersInput: false,
      isEnableOptions: [
        { value: 0, label: '停用' },
        { value: 1, label: '启用' }
      ],
      mailTypeOptions: [],
      executeStateOptions: [],
      dataSource: [], // [{ ExecutionTimes: 4, ExecuteState: 4, Id: 1 }, { ExecutionTimes: 2, ExecuteState: 4 }],
      selectedId: [], // 选中的id
      tableLoading: false,
      // 编辑发送记录
      dialogTemplate: false,
      isAddRecord: true,
      recordParamsDto: {
        ExecuteState: 1
      },
      allMailTemplates: [],
      templateParamsRules: {
        ReceiverName: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' }],
        ReceiverEmail: [{ required: true, message: '请输入收件人邮箱地址', trigger: 'blur' }],
        EstimatedTime: [{ required: true, message: '请输入预计发送时间', trigger: 'blur' }],
        ExecuteState: [{ required: true, message: '请选择邮发送状态', trigger: 'change' }],
        MailType: [{ required: true, message: '请选择邮件类型', trigger: 'change' }],
        MailTemplateId: [{ required: true, message: '请选择邮件模版', trigger: 'change' }]
      }
    }
  },
  computed: {
    getRecordTitle() {
      return this.isAddRecord ? '新增发送记录' : '编辑发送记录'
    }
  },
  created() {
    getEnumsGetDes('MailTypeEnum').then((res) => {
      this.mailTypeOptions = res
    })
    getEnumsGetDes('MailStateEnum').then((res) => {
      this.executeStateOptions = res
    })
    _getAllMailTemplates().then((res) => {
      this.allMailTemplates = res
    })
    this.serarch()
  },
  methods: {
    // 返回枚举类型名称
    getMailType(type) {
      if (this.mailTypeOptions.length === 0) return ''
      const findObj = this.mailTypeOptions.find(item => item.Id === type)
      return findObj.Name || ''
    },
    getExecuteState(type) {
      if (this.executeStateOptions.length === 0) return ''
      const findObj = this.executeStateOptions.find(item => item.Id === type)
      return findObj.Name || ''
    },
    // 分页
    pagerSerach(page) {
      // if (page === 1) return
      this.pagerDto.PageIndex = page
      this.serarch()
    },
    sizeChange(pageSize) {
      this.pagerDto.PageIndex = 1
      this.pagerDto.PageSize = pageSize
      this.serarch()
    },
    // 查询
    serarch() {
      this.tableLoading = true
      _queryMailRecordPage(this.pagerDto)
        .then((response) => {
          this.dataSource = response.Result
          this.pagerDto.total = response.TotalCount
        })
        .finally((response) => {
          this.tableLoading = false
        })
    },
    // 选中
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.selectedId = val.map((item) => item.Id)
      }
    },
    // 重新发送
    hanleResend() {
      if (this.selectedId.length === 0) {
        this.$message({ type: 'warning', message: '请选择重发邮件！' })
        return
      }
      _retrySend(this.selectedId).then(() => {
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
      })
    },
    // 新增、修改
    hanleSubmitTemplate() {
      this.$refs.recordFormRef.validate((valid) => {
        if (valid) {
          _saveMailRecord(this.recordParamsDto).then(() => {
            this.$message({
              type: 'success',
              message: '保存成功!'
            })
          })
        } else {
          return false
        }
      })
    },
    // 编辑弹窗
    addEditMailRecord(data) {
      this.isAddRecord = true
      if (data) {
        this.isAddRecord = false
        this.recordParamsDto = data
        this.$set(this.recordParamsDto, 'MailTemplateId', data.Id)
      }
      this.$nextTick(() => {
        this.dialogTemplate = true
      })
    },
    handleCloseRecord() {
      this.recordParamsDto = {}
      this.$refs.recordFormRef.resetFields()
      this.dialogTemplate = false
    },
    // 处理多个订单号
    openNumbersInputPannel() {
      const str = format(this.pagerDto._In_Number, '\n')
      this.inputMultiCodes = str
      this.openNumbersInput = true
    },
    confirmMultiCodes() {
      const inputs = this.inputMultiCodes
      const str = format(inputs, ',')
      this.pagerDto._In_Number = str
      this.inputMultiCodes = ''
      this.openNumbersInput = false
    }
  }
}
</script>
<style>
.sendRecord {
  background-color: #f3f3f3;
  padding: 20px;
}
.sendRecord .record-form .el-form-item__label {
  text-align: left;
}
.record-form .el-form-item ,
.record-form .el-form-item__content {
  width: calc(100% - 20px);
}
.record-form .el-form-item__content .el-select,
.sendRecord .el-form-item__content .estimated-time {
  width: 100%;
}
@media screen and (max-width: 1400px) {
  .record-form .el-col-12 {
    width: 100%;
  }
}
</style>

