<template>
  <div class="app-container">
    <el-form v-model="pagerDto" inline>
      <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 label="签收人">
        <el-select
          v-model="pagerDto._Eq_SignUserName"
          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 label="始发地">
        <el-select
          v-model="pagerDto._Eq_Origin"
          placeholder="始发地"
          clearable
          filterable
        >
          <el-option
            v-for="item in transferPoints"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="目的地">
        <el-select
          v-model="pagerDto._Eq_Destination"
          placeholder="目的地"
          clearable
          filterable
        >
          <el-option
            v-for="item in transferPoints"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="pagerDto._Eq_Status" placeholder="状态" clearable>
          <el-option
            v-for="(item, index) in statuss"
            :key="index"
            :value="item.Id"
            :label="item.Name"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="pagerDto._Eq_TimeType"
          placeholder="时间类型"
          clearable
          filterable
        >
          <el-option
            v-for="item in timeTypes"
            :key="item.Id"
            :label="item.Name"
            :value="item.Id"
          />
        </el-select>
        <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-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_BatchNumber"
            clearable
            @focus="openNumbersInputPannel"
          />
        </el-tooltip>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          type="success"
          @click="searchData"
        >搜索</el-button>
        <el-button
          :loading="downloading"
          type="primary"
          icon="el-icon-download"
          @click="downRecords"
        >导出记录</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table
        v-loading="loading"
        :data="sourceData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column prop="BatchNumber" label="批次号" width="200" />
        <el-table-column prop="Origin" label="始发地" width="120" />
        <el-table-column prop="Destination" label="目的地" width="120" />
        <el-table-column prop="Cost" label="成本" width="100" />
        <el-table-column prop="StatusName" label="状态" width="100" />
        <el-table-column prop="CreateUserName" label="创建人" width="100" />
        <el-table-column prop="CreateTime" label="创建时间" width="200" />

        <el-table-column prop="SignUserName" label="签收人" width="100" />
        <el-table-column prop="SignTime" label="签收时间" width="200" />

        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              :disabled="scope.row.Status == 1"
              type="success"
              size="mini"
              plain
              @click="openSign(scope.row)"
            >签收</el-button>
            <el-button
              type="danger"
              size="mini"
              plain
              @click="remove(scope.row)"
            >移除</el-button>
            <el-button
              type="primary"
              size="mini"
              plain
              @click="openSetCost(scope.row)"
            >录入运费</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        :page-sizes="[100, 200, 300, 400]"
        :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"
      />
    </div>
    <el-dialog
      title="提示"
      :visible.sync="showSignConfirm"
      :handle-close="dialogClose"
      width="30%"
    >
      <span>确定签收吗</span>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            currentBatch = {};
            showSignConfirm = false;
          "
        >取 消</el-button>
        <el-button type="primary" @click="sign">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="`录入成本(${!!currentBatch ? currentBatch.BatchNumber : null})`"
      :visible.sync="showSetCost"
      :handle-close="dialogClose"
      width="30%"
    >
      <span />
      <el-form>
        <el-form-item label="运费成本">
          <el-input v-model="currentBatch.Cost" type="number" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            currentBatch = {};
            showSetCost = false;
          "
        >取 消</el-button>
        <el-button type="primary" @click="setCost">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import request from '@/utils/request'
import { _getAllUsers } from '@/api/baseInfo'
import { getToken } from '@/utils/auth'
import { parseJSON } from 'date-fns'
import { format } from '@/utils/multiInput'
import colFormatDate from '@/utils/columnFormat'
import { _getBatchTransferPoint, _setCost, _sign } from '@/api/batchTransfer'
export default {
  name: 'BatchTransfer',
  data() {
    return {
      currentBatch: {},
      showSetCost: false,
      showSignConfirm: false,
      downloading: false,
      inputMultiCodes: '',
      openNumbersInput: false,
      loading: false,
      selectedItems: [],
      transferPoints: [],
      users: [],
      customers: [],
      channels: [],
      timeRange: [],
      statuss: [
        { Id: 0, Name: '未转运' },
        { Id: 1, Name: '已转运' }
      ],
      timeTypes: [
        { Id: 0, Name: '创建时间' },
        { Id: 1, Name: '签收时间' }
      ],
      CodeTypes: [
        { Name: '中转单号', Id: 1 },
        { Name: '跟踪号', Id: 2 }
      ],
      editItem: {},
      sourceData: [],
      pagerDto: {
        _Eq_CreateUserName: null,
        _Eq_CodeType: null,
        _Eq_TimeType: null,
        _In_BatchNumber: '',
        _LeE_EndTime: null,
        _GrE_StartTime: null,
        PageIndex: 1,
        PageSize: 100,
        total: 0
      }
    }
  },
  created() {
    this.getBatchTransferPoint()
    _getAllUsers().then((resp) => {
      this.users = resp
    })
    this.pagerDto.PageIndex = 1
    this.pagerDto._Eq_ChannelId = ''
    this.searchData()
  },
  methods: {
    dialogClose() {
      this.currentBatch = {}
    },
    openSetCost(item) {
      this.currentBatch = item
      this.showSetCost = true
    },
    setCost() {
      const batchNumber = this.currentBatch.BatchNumber
      const cost = this.currentBatch.Cost
      const data = { batchNumber, cost }
      _setCost(data).then((res) => {
        this.showSetCost = false
        this.$message({ type: 'success', message: '设置成功' })
        this.currentBatch = {}
      })
    },
    openSign(item) {
      this.currentBatch = item
      this.showSignConfirm = true
    },
    sign() {
      const id = this.currentBatch.Id
      const data = { id }
      _sign(data).then((res) => {
        const idx = this.sourceData.findIndex((i) => i.Id == res.Id)
        if (idx > -1) {
          this.sourceData[idx].Status = res.Status
          this.sourceData[idx].StatusName = res.StatusName
          this.sourceData[idx].SignUserName = res.SignUserName
          this.sourceData[idx].SignTime = res.SignTime
          this.currentBatch = {}
          this.showSignConfirm = false
          this.$message({ type: 'success', message: '签收成功' })
        }
      })
    },
    getBatchTransferPoint() {
      _getBatchTransferPoint().then((res) => {
        this.transferPoints = res
      })
    },
    colFormatDate,
    downRecords() {
      this.downloading = true
      var url = `${process.env.VUE_APP_BASE_API}/TransferBatch/Down`
      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.downloadLoading = false
      }
      const data = JSON.stringify(this.pagerDto)
      x.send(data)
    },
    openNumbersInputPannel() {
      const str = format(this.pagerDto._In_BatchNumber, '\n')
      this.inputMultiCodes = str
      this.openNumbersInput = true
    },
    confirmMultiCodes() {
      const inputs = this.inputMultiCodes
      const str = format(inputs, ',')
      this.pagerDto._In_BatchNumber = str
      this.inputMultiCodes = ''
      this.openNumbersInput = false
    },

    timeRangeSeleted(dateRange) {
      this.pagerDto._GrE_StartTime = dateRange[0]
      this.pagerDto._LeE_EndTime = dateRange[1]
    },
    sizeChange(s) {
      this.pagerDto.PageSize = s
      this.searchData()
    },
    handleSelectionChange(val) {
      this.selectedItems = val
    },
    searchData() {
      this.loading = true
      request({
        url: '/TransferBatch/query',
        method: 'post',
        data: this.pagerDto
      })
        .then((resp) => {
          this.loading = false
          this.pagerDto.total = resp.TotalCount
          this.pagerDto.PageIndex = resp.PageIndex

          this.sourceData = resp.Result
        })
        .finally(() => {
          this.loading = false
        })
    },
    remove(item) {
      this.$confirm('是否删除该转运批次?', '正在删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        request({
          url: '/TransferBatch/Delete',
          params: { id: item.Id },
          method: 'post'
        })
          .then((resp) => {
            if (resp.success === true) {
              this.$message({ message: '删除成功', type: 'success' })
              const idx = this.sourceData.findIndex((i) => i.Id === item.Id)
              this.sourceData.splice(idx, 1)
            } else {
              const msg = resp.message
              this.$message({ message: msg, type: 'error' })
            }
          })
          .catch(() => {
            this.$message({ message: '删除出错', type: 'error' })
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    pagerSerach(p) {
      this.pagerDto.PageIndex = p
      this.searchData()
    }
  }
}
</script>
<style scoped></style>
