<template>
  <base-list>
    <template slot="n_header">
      <el-form v-model="pagerDto" inline>
        <el-form-item label="箱号">
          <multi-input v-model="pagerDto._In_BoxNumber" />
        </el-form-item>
        <el-form-item label="批号">
          <multi-input v-model="pagerDto._In_BatchNo" />
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            value-format="yyyy-MM-dd"
            end-placeholder="结束日期"
            @change="timeRangeSeleted"
          />
        </el-form-item>
        <el-form-item label="创建人">
          <el-select
            v-model="pagerDto._Eq_CreateUserName"
            placeholder="创建人"
            clearable
            filterable
          >
            <el-option
              v-for="item in users"
              :key="item.Id"
              :label="item.Name"
              :value="item.Name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button type="success" @click="openCreate">批量创建箱子</el-button>
          <el-button type="info" @click="exportData">导出</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template slot="n_option">
      <el-form>
        <el-form-item label="导出模板">
          <el-select v-model="templateId">
            <el-option
              v-for=" item in templateList"
              :key="item.Name"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template>
      <el-table
        v-loading="dataLoading"
        :data="data"
        :highlight-current-row="true"
        :select-on-indeterminate="true"
        width="100%"
      >
        <el-table-column prop="BatchNo" label="批号" />
        <el-table-column prop="BoxNumber" label="箱号" />
        <el-table-column prop="CreateUserName" label="创建人" />
        <el-table-column prop="CreateTime" label="创建时间" />
        <el-table-column prop="ChannelName" label="渠道名称" />
        <el-table-column prop="ChannelCode" label="渠道代码" />
        <el-table-column prop="ParcelQty" label="订单数量" />
        <el-table-column prop="ParcelQty" label="状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsDelivery == true" type="success">已装箱</el-tag>
            <el-tag v-else type="warning">未装箱</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350px">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              @click="downBoxLabel(scope.row.BoxNumber)"
            >下载标签</el-button>
            <el-button
              v-if="!!scope.row.BatchNo"
              size="small"
              type="success"
              @click="downBatchLabel(scope.row.BatchNo)"
            >下载整批标签</el-button>

            <el-button
              v-if="!!scope.row.BatchNo"
              size="small"
              type="danger"
              @click="deleteBox(scope.row.Id)"
            >删除箱子</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[10, 20, 40, 100, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size.sync="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @size-change="changePager"
        @current-change="pagerSerach"
      />
    </template>
    <el-dialog
      title="批量创建箱子"
      :visible.sync="createDialogVisible"
      width="30%"
      :before-close="cancelCreate"
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="form" :model="createDto" :rules="rules">
          <el-form-item label="批号" prop="batchNo">
            <el-input v-model="createDto.batchNo" readonly>
              <template slot="append">
                <el-button @click="regenBatchNo">重新生成</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="渠道" prop="channelId">
            <el-select
              v-model="createDto.channelId"
              placeholder="渠道"
              clearable
              filterable
            >
              <el-option
                v-for="item in channels"
                :key="'channel1' + item.Id"
                :value="item.Id"
                :label="item.Name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="国家">
            <el-select v-model="createDto.country" filterable>
              <el-option
                v-for="(item, index) in countries"
                :key="index"
                :label="item.CnName"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="口岸">
            <el-input v-model="createDto.port" />
          </el-form-item>
          <el-form-item label="数量" prop="count">
            <el-input-number v-model="createDto.count" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelCreate">取 消</el-button>
        <el-button type="primary" @click="submitBatchCreate">确 定</el-button>
      </span>
    </el-dialog>
  </base-list>
</template>
<script>
import date from 'date-and-time'
import { _getDeliverChannel, _getCountries, _getAllUsers } from '@/api/baseInfo'
import BaseList from '@/components/Xyy/baselist'
import { _createBoxes, _getBoxPage, _exportData, _deleteBox } from '@/api/transfer/box'
import multiInput from '@/components/Xyy/multiInput.vue'
import { getToken } from '@/utils/auth'
import { _getList } from '@/api/transfer/template'
export default {
  name: 'CreateBoxes',
  components: { 'base-list': BaseList, multiInput },
  data() {
    return {
      currentBatchNo: null,
      createDialogVisible: false,
      timeRange: [],
      channels: [],
      countries: [],
      users: [],
      batchNo: '',
      boxNumbers: '',
      data: [],
      templateList: [],
      dataLoading: false,
      templateId: 0,
      createDto: {
        batchNo: null,
        count: null,
        channelId: null,
        port: null
      },
      pagerDto: {
        PageIndex: 0,
        PageSize: 10,
        total: 0,
        _In_BoxNumber: null,
        _In_BatchNo: null,
        QuerySort: [{ Field: 'Id', IsDesc: true }]
      },
      rules: {
        batchNo: [{ required: true, message: '请输入批次号', trigger: 'blur' }],
        channelId: [{ required: true, message: '请选择渠道', trigger: 'change' }],
        count: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          {
            type: 'number',
            required: true,
            min: 1,
            max: 9999,
            message: '至少1个箱子',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    timeRange(n, v) {
      if (!n) {
        this.pagerDto._GrE_CreateTime = null
        this.pagerDto._LeE_CreateTime = null
      }
    }
  },
  created() {
    _getDeliverChannel().then((resp) => {
      this.channels = resp
    })

    _getCountries().then((res) => {
      this.countries = res
    })

    _getAllUsers().then((resp) => {
      this.users = resp
    })
    _getList().then(r => {
      this.templateList.push({ Id: 0, Name: '无' })
      for (var i = 0; i < r.length; i++) {
        this.templateList.push(r[i])
      }
    })
  },
  mounted() {
    this.pagerSerach(1)
  },
  methods: {
    deleteBox(boxId) {
      this.$confirm('是否删除箱子？').then((res) => {
        if (!boxId || boxId < 0) {
          this.$message({ type: 'error', message: '箱子ID无效' })
          return
        }
        _deleteBox(boxId).then((res) => {
          if (res.Success == true) {
            const idx = this.data.findIndex((b) => b.Id == boxId)
            if (idx > -1) {
              this.data.splice(idx, 1)
            }

            this.$message({ type: 'success', message: '箱子删除成功' })
          }
        })
      })
    },
    exportData() {
      this.dataLoading = true
      var url = `${process.env.VUE_APP_BASE_API}/PKG/DownBatchBoxData`
      var x = new XMLHttpRequest()
      x.open('POST', url, true)
      x.responseType = 'blob'
      x.setRequestHeader('content-type', 'application/json')
      x.setRequestHeader('token', getToken())

      x.onload = (e) => {
        this.downloading = false
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a')
        a.href = url
        a.download = `批量箱子记录.xls`
        a.click()
        this.dataLoading = false
      }
      const data = JSON.stringify(this.pagerDto)
      x.send(data)
    },
    timeRangeSeleted(dateRange) {
      this.pagerDto._GrE_CreateTime = dateRange[0]
      this.pagerDto._LeE_CreateTime = dateRange[1]
    },
    downBoxLabel(boxNumber) {
      if (this.templateId == 0 || !this.templateId) {
        window.open(
          `${process.env.VUE_APP_BASE_API}/PKG/DownLoadBoxPdf?batchNo=&boxNumber=${boxNumber}`,
          '_blank'
        )
      } else {
        window.open(
          `${process.env.VUE_APP_BASE_API}/BoxTemplate/GetLabels?batchNo=&boxNumber=${boxNumber}&TemplateId=${this.templateId}`,
          '_blank')
      }
    },
    downBatchLabel(batchNo) {
      if (this.templateId == 0 || !this.templateId) {
        window.open(
          `${process.env.VUE_APP_BASE_API}/PKG/DownLoadBoxPdf?batchNo=${batchNo}&boxNumber=`,
          '_blank'
        )
      } else {
        window.open(
          `${process.env.VUE_APP_BASE_API}/BoxTemplate/GetLabels?batchNo=${batchNo.trim()}&boxNumber=&TemplateId=${this.templateId}`,
          '_blank')
      }
    },
    cancelCreate() {
      this.createDialogVisible = false
    },
    generateBatchNo() {
      const now = new Date()
      const serialNum = date.format(now, 'BBYYMMDDHHmmss')
      return serialNum
    },
    regenBatchNo() {
      const batchNo = this.generateBatchNo()
      this.createDto.batchNo = batchNo
    },
    openCreate() {
      this.createDto.batchNo = this.generateBatchNo()
      this.createDialogVisible = true
    },
    submitBatchCreate() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = this.createDto
          _createBoxes(data).then((res) => {
            if (res.Success == false) {
              const msg = res.Message || '生成失败'
              this.$message({ message: msg, type: 'error' })
              return
            }
            this.createDialogVisible = false
            this.$message({ message: '生成成功', type: 'success' })
            const batchNo = res.message
            console.log(res)
            if (this.templateId == 0 || !this.templateId) {
              window.open(
                `${process.env.VUE_APP_BASE_API}/PKG/DownLoadBoxPdf?batchNo=${batchNo}&boxNumber=`,
                '_blank'
              )
            } else {
              window.open(
                `${process.env.VUE_APP_BASE_API}/BoxTemplate/GetLabels?batchNo=${batchNo.trim()}&boxNumber=&TemplateId=${this.templateId}`,
                '_blank')
            }
          })
        } else {
          return false
        }
      })
    },
    updateBoxNumbers(val) {
      this.boxNumbers = val
    },
    search() {
      this.pagerSerach()
    },
    show() {},
    pagerSerach(index) {
      this.dataLoading = true
      if (index) {
        this.pagerDto.PageIndex = index
      }
      const data = this.pagerDto
      _getBoxPage(data)
        .then((res) => {
          this.data = res.Result
          this.pagerDto.total = res.TotalCount
        })
        .finally((res) => {
          this.dataLoading = false
        })
    },
    changePager(v) {
      this.PageSize = v
      this.pagerSerach()
    }
  }
}
</script>
