<template>
  <div class="app-container">
    <el-form v-model="pagerDto" inline>
      <el-form-item label="操作类型">
        <el-select v-model="pagerDto._Eq_OperationType" placeholder="操作类型" clearable>
          <el-option
            v-for="(item, index) in operateTypes"
            :key="index"
            :value="item.Id"
            :label="item.Name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作人">
        <el-select
          v-model="pagerDto._Eq_OperationUserName"
          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-date-picker
          v-model="timeRange"
          placeholder=""
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          value-format="yyyy-MM-dd"
          end-placeholder="结束日期"
          @change="TimeRangeSeleted"
        />
      </el-form-item>
      <el-form-item label="渠道" prop="ChannelId">
        <el-select v-model="pagerDto._Eq_ChannelId" filterable clearable>
          <el-option
            v-for="item in channels"
            :key="item.Id"
            :label="item.Name"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单号类型">
        <el-select v-model="pagerDto._Eq_CodeType" placeholder="单号类型" clearable>
          <el-option
            v-for="(item, index) in CodeTypes"
            :key="index"
            :value="item.Id"
            :label="item.Name"
          />
        </el-select>
      </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_Codes"
            clearable
            @focus="openNumbersInputPannel"
          />
        </el-tooltip>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="pagerDto._Eq_OrderStatus" 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-button
          icon="el-icon-search"
          type="success"
          @click="searchData"
        >搜索</el-button>
        <el-button
          :loading="downloading"
          type="primary"
          icon="el-icon-download"
          @click="openCreateTransferBatch"
        >生成批次</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="TransferNumber" label="转单号" width="200" />
        <el-table-column prop="TrackingNumber" label="跟踪号" width="200" />
        <el-table-column prop="ChannelName" label="渠道" width="200" />
        <el-table-column prop="OpWeight" label="重量" width="200" />
        <el-table-column prop="StatusName" label="状态" width="100" />
        <el-table-column prop="OperationName" label="操作类型" width="200" />
        <el-table-column prop="OperationUserName" label="操作人" width="200" />
        <el-table-column
          prop="OperationTime"
          label="称重时间"
          :formatter="colFormatDate"
        />
        <el-table-column label="操作" width="100">
          <template slot-scope="scope" />
        </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>
    <div>
      <el-dialog :title="`创建转运批次 (共${selectedItems && selectedItems.length>0?selectedItems.length:0}个订单)`" :visible.sync="dialogVisible" width="30%">
        <div>
          <el-form>
            <el-form-item label="始发地">
              <el-select
                v-model="createTransferBatchDto.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="createTransferBatchDto.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="运费" label-width="4em">
              <el-input
                v-model="createTransferBatchDto.cost"
                type="number"
                style="width: 100px"
              />
            </el-form-item>
          </el-form>
        </div>
        <div>
          <div v-show="!!createResultMsg" style="color: #67c23a">
            {{ createResultMsg }}
          </div>
          <div class="result-wrap">结果批次号</div>
          <div style="text-align: center">
            <el-input
              ref="txtBatchNumber"
              v-model="resultBatchNumber"
              readonly
              style="width: 70%;"
              size="large"
            />
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="createTransferBatch">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import request from '@/utils/request'
import { _getAllUsers, _getDeliverChannel } from '@/api/baseInfo'

import { format } from '@/utils/multiInput'
import colFormatDate from '@/utils/columnFormat'
import {
  _getBatchTransferPoint,
  _queryOrderForTransferBatch,
  _createTransferBatch
} from '@/api/batchTransfer'
export default {
  name: 'CreateBatchTransfer',
  data() {
    return {
      createResultMsg: null,
      resultBatchNumber: null,
      dialogVisible: false,
      downloading: false,
      inputMultiCodes: '',
      openNumbersInput: false,
      loading: false,
      selectedItems: [],
      transferPoints: [],
      users: [],
      customers: [],
      channels: [],
      timeRange: [],
      statuss: [
        { Id: 1, Name: '待揽收' },
        { Id: 2, Name: '待装箱' },
        { Id: 3, Name: '已装箱' }
      ],
      operateTypes: [
        { Id: 0, Name: '称重' },
        { Id: 1, Name: '装箱' }
      ],
      timeTypes: [
        { Id: 0, Name: '称重时间' },
        { Id: 1, Name: '装箱时间' }
      ],
      CodeTypes: [
        { Name: '跟踪号', Id: 0 },
        { Name: '中转单号', Id: 1 }
      ],
      editItem: {},
      sourceData: [],
      pagerDto: {
        _Eq_OperationType: 0,
        _Eq_CodeType: 0,
        _Eq_TimeType: null,
        _In_Codes: '',
        _Eq_ChannelId: null,
        _GrE_StartTime: null,
        _LeE_EndTime: null,
        PageIndex: 1,
        PageSize: 100,
        total: 0
      },
      createTransferBatchDto: {
        origin: null,
        destination: null,
        orderIds: []
      }
    }
  },
  created() {
    const today = new Date()
    const yesterday = today.setDate(today.getDate() - 1)

    _getAllUsers().then((resp) => {
      this.users = resp
    })
    _getDeliverChannel().then((resp) => {
      this.channels = resp
    })
    _getBatchTransferPoint().then((res) => {
      this.transferPoints = res
    })

    this.pagerDto.PageIndex = 1
    this.pagerDto._Eq_ChannelId = ''
    // this.searchData();
  },
  methods: {
    colFormatDate,
    openCreateTransferBatch() {
      if ((!this.selectedItems || this.selectedItems.length == 0)) {
        this.$message({ type: 'error', message: '请先选择订单' })
        return
      } else {
        this.dialogVisible = true
      }
    },

    createTransferBatch() {
      if (!this.createTransferBatchDto.origin) {
        this.$message({ type: 'error', message: '请先设置始发地' })
        return
      }
      if (!this.createTransferBatchDto.destination) {
        this.$message({ type: 'error', message: '请先设置目的地' })
        return
      }
      if (this.createTransferBatchDto.origin == this.createTransferBatchDto.destination) {
        this.$message({ type: 'error', message: '始发地不能和目的地相同' })
        return
      }
      if (!this.selectedItems || this.selectedItems.length <= 0) {
        this.$message({ type: 'error', message: '请先搜索并选择订单' })
        return
      }
      const ids = this.selectedItems.map((i) => i.OrderId)
      this.createTransferBatchDto.orderIds = ids
      const data = this.createTransferBatchDto
      _createTransferBatch(data).then((res) => {
        const batchNumber = res.BatchNumber
        this.resultBatchNumber = batchNumber
        this.createResultMsg = '创建批次成功！'
      })
    },
    queryAndCreateTransferBatch() {},
    openNumbersInputPannel() {
      const str = format(this.pagerDto._In_Codes, '\n')
      this.inputMultiCodes = str
      this.openNumbersInput = true
    },
    confirmMultiCodes() {
      const inputs = this.inputMultiCodes
      const str = format(inputs, ',')
      this.pagerDto._In_Codes = str
      this.inputMultiCodes = ''
      this.openNumbersInput = false
    },

    TimeRangeSeleted(dateRange) {
      this.pagerDto._GrE_StartTime = dateRange[0]
      this.pagerDto._LeE_EndTime = dateRange[1]
    },

    handleSelectionChange(val) {
      this.selectedItems = val
    },
    searchData() {
      this.loading = true
      const data = this.pagerDto
      _queryOrderForTransferBatch(data)
        .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: '/ClaimRecord/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()
    },
    sizeChange(s) {
      this.pagerDto.PageSize = s
      this.searchData()
    }
  }
}
</script>
<style scoped>
.result-wrap {
  margin-bottom: 10px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}
</style>
