<template>
  <div class="esuibao">
  <el-dialog title="下载待同步轨迹" :visible.sync="dialogShowDownTracking">
    <el-card shadow="never" style="margin-bottom:20px;">
      <el-form v-model="paramsDto" inline>
        <el-form-item label="收件天数">
          <el-input v-model="paramsDto.onReceiverTime" oninput="value=value.replace(/[^\d]/g, '')" />
        </el-form-item>
        <el-form-item label="是否包含签收">
          <el-select
            v-model="paramsDto.isHasSign"
            clearable
          >
            <el-option
              v-for="item in signReceipt"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            />
          </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="inputMultiOrders"
                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="inputMultiOrders = ''"
                >清除</el-button>
                <el-button
                  size="mini"
                  type="success"
                  @click="confirmMultiOrders"
                >确定</el-button>
              </div>
            </div>
            <el-input
              v-model="inNumbers"
              clearable
              @focus="openNumbersInputOrder"
            />
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="dataLoading" @click="downExcel">导出记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-dialog>

  <el-dialog title="下载收寄信息" :visible.sync="dialogShowDownSJXX">
    <el-card shadow="never" style="margin-bottom:20px;">
      <el-form v-model="trackingMoreParamsDto" inline>
        <el-form-item label="时间">
          <el-date-picker
            v-model="timeRange"
            type="daterange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </el-form-item>
        <el-form-item>
          <div class="btns">
            <el-select v-model="trackingMoreParamsDto.DownloadType" placeholder="请选择下载内容" style="width: 145px;">
              <el-option
                v-for="item in optionsButton"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                style="padding: 0;margin-bottom: 3px;"
              >
                <el-button :loading="loadGetESBJJ" :type="item.type" style="width: 100%;" @click="hanleDownloadType(item.value)">{{ item.label }}</el-button>
              </el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    </el-dialog>

    <div class="title">同步记录</div>
      <el-card shadow="never" style="margin-bottom:20px;">
      <el-form v-model="pagerDto" inline>
          <el-form-item label="轨迹时间">
            <el-date-picker
              v-model="timeRange2"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label="单号组">
            <el-tooltip v-model="openNumbersInput2" effect="light" :manual="true">
              <div slot="content">
                <el-input
                  v-model="tempNum"
                  type="textarea"
                  rows="7"
                  placeholder="请输入单号，每行一个"
                />
                <div style="text-align: right; padding: 5px">
                  <el-button
                    size="mini"
                    @click="openNumbersInput2 = false"
                  >关闭</el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="tempNum = ''"
                  >清除</el-button>
                  <el-button
                    size="mini"
                    type="success"
                    @click="confirmMultiOrders2"
                  >确定</el-button>
                </div>
              </div>
              <el-input
                v-model="pagerDto._In_trackNum"
                clearable
                @focus="openNumbersInputOrder2"
              />
            </el-tooltip>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="pagerDto._Eq_PushStatus" clearable>
              <el-option v-for="option in options" :label="option.Title" :value="option.Status"></el-option>
            </el-select>
          </el-form-item>
        <el-form-item>
          <el-button @click="serarch()" type="primary">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="retryList()">重试</el-button>
        </el-form-item>
        <el-form-item>
          <el-button  @click="dialogShowDownTracking=true">下载待同步轨迹</el-button>
        </el-form-item>
        <el-form-item>
          <el-button   @click="dialogShowDownSJXX=true">下载收寄信息</el-button>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loadGetESBJJ" @click="DownAMTracking()">下载AM轨迹</el-button>
        </el-form-item>
        </el-form>
      </el-card>
      <el-card shadow="never" style="margin-bottom:20px;">
        <el-table :data="logs"  :highlight-current-row="true" :select-on-indeterminate="true" width="100%" :height="570" border @selection-change="onSelection">
          <el-table-column type="selection"  :selectable="rowCanSelect" />
          <el-table-column label="单号" prop="trackNum" width="200" />
          <el-table-column label="位置" prop="location"/>
          <el-table-column label="物流状态" prop="state"  />
          <el-table-column label="轨迹时间" prop="time" />
          <el-table-column label="国家" prop="country"  />
          <el-table-column label="同步状态" prop="PushStatus" >
            <template slot-scope="r">
              {{r.row.PushStatus == 0 ? "未推送" : r.row.PushStatus ==1 ? "已推送" : "推送失败"}}
            </template>
          </el-table-column>
        <el-table-column label="异常" prop="ResultMsg" width="200" />
          <el-table-column label="同步时间" prop="CreateTime" >
            <template slot-scope="r">
              {{r.row.CreateTime.replace('T',' ').substring(0,19)}}
            </template>
          </el-table-column>
        </el-table>
        <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="serarch"
        />
      </el-card>

  </div>
</template>
<script>
// import BaseList from '@/components/Xyy/baselist'
// import { _downTest } from '@/api/tracking/esuibao'
import { getToken } from '@/utils/auth'
import { format } from '@/utils/multiInput'
import { QueryPager,Retry } from '@/api/esb'
import axios from 'axios'
export default {
  name: 'ESuibaoTrack',
  // components: { 'base-list': BaseList },
  data() {
    return {
      pagerDto:{
        _In_trackNum:'',
        _Eq_Status:'',
        PageIndex:1,
        PageSize:100,
        total:0
      },
      logs:[],
      options:[
        {'Status':0,'Title':'未推送'},
        {'Status':1,'Title':'已推送'},
        {'Status':2,'Title':'推送失败'},
      ],
      timeRange2:[],
      dataLoading: false,
      dialogShowDownSJXX:false,
      dialogShowDownTracking:false,
      openNumbersInput2: false, // 显示/隐藏单号组
      openNumbersInput: false, // 显示/隐藏单号组
      inputMultiOrders: '', // 保存单号组
      signReceipt: [
        {
          label: '是',
          value: true,
          id: '1receipt'
        },
        {
          label: '否',
          value: false,
          id: '2receipt'
        }
      ],
      // 导出参数
      inNumbers: '',
      paramsDto: {
        onReceiverTime: undefined,
        isHasSign: true,
        Numbers: []
      },
      tempNum:'',
      // 下载寄件信息参数
      trackingMoreParamsDto: {
        StartTime: undefined,
        EndTime: undefined,
        DownloadType: undefined
      },
      loadGetESBJJ: false,
      timeRange: [],
      multipleSelection:[],
      keys:[],
      optionsButton: [
        {
          value: 2,
          label: '全部',
          type: 'success'
        },
        {
          value: 0,
          label: '仅未下载',
          type: 'primary'
        },
        {
          value: 1,
          label: '仅已下载',
          type: 'primary'
        }
      ]
    }
  },
  methods: {
    // 导出
    rowCanSelect(row) {
      return row.PushStatus ==2
    },
    downExcel() {
      this.dataLoading = true
      const arrNumbers = this.inNumbers.split(',')
      if (arrNumbers.length > 0) {
        this.paramsDto.Numbers = arrNumbers.filter(item => item)
      }
      this.paramsDto.onReceiverTime = Number(this.paramsDto.onReceiverTime) || undefined
      // _downTest(this.paramsDto).then(res => {
      //   console.log(res, 'res')
      // })
      axios({
        method: 'post',
        url: 'http://wms.xingyunyi.cn/api/TrackingMore/GetESBTrackingFile',
        data: JSON.stringify(this.paramsDto),
        responseType: 'blob',
        headers: { 'Content-Type': 'application/json', 'Token': getToken() }
      })
        .then((res) => {
          console.log(res)
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
          const fileName = Date.parse(new Date()) + 'E速宝轨迹.xlsx'
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            // 释放内存
            window.URL.revokeObjectURL(link.href)
          }
        })
        .catch((error) => {
          const msg = error.name + error.message
          this.$alert(msg, '错误', { type: 'error' })
        }).finally(() => {
          this.dataLoading = false
        })
      console.log(this.paramsDto, ':this.paramsDto')
    },
    retryList(){
      Retry(this.keys).then(r=>{
        this.$message({ type: 'success', message: '重试成功' })
        this.serarch(1)
      })
    },
    // 单号组
    openNumbersInputOrder() {
      const str = format(this.inNumbers, '\n')
      this.inputMultiOrders = str
      this.openNumbersInput = true
    },
    // 提示框确定单号
    confirmMultiOrders() {
      const inputs = this.inputMultiOrders
      const str = format(inputs, ',')
      this.inNumbers = str
      this.inputMultiOrders = ''
      this.openNumbersInput = false
    },
    // 单号组
    openNumbersInputOrder2() {
      const str = format(this.pagerDto._In_trackNum, '\n')
      this.tempNum = str
      this.openNumbersInput2 = true
    },
    // 提示框确定单号
    confirmMultiOrders2() {
      debugger
      const inputs = this.tempNum
      const str = format(inputs, ',')
      this.pagerDto._In_trackNum = str
      this.tempNum = ''
      this.openNumbersInput2 = false
    },
    // 下载收寄信息
    hanleDownloadType(type) {
      // if (this.timeRange.length === 0) {
      //   this.$message({
      //     message: '请选择时间！',
      //     type: 'warning'
      //   })
      //   return false
      // }
      this.loadGetESBJJ = true
      // 时间
      this.trackingMoreParamsDto.StartTime = this.timeRange[0]
      this.trackingMoreParamsDto.EndTime = this.timeRange[1]
      this.trackingMoreParamsDto.DownloadType = type
      // console.log(this.trackingMoreParamsDto, ':trackingMoreParamsDto')
      axios({
        method: 'post',
        url: 'http://wms.xingyunyi.cn/api/TrackingMore/GetESBJJ',
        data: JSON.stringify(this.trackingMoreParamsDto),
        responseType: 'blob',
        headers: { 'Content-Type': 'application/json', 'Token': getToken() }
      })
        .then((res) => {
          console.log(res)
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
          const fileName = Date.parse(new Date()) + '收寄信息.xlsx'
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            // 释放内存
            window.URL.revokeObjectURL(link.href)
          }
        })
        .catch((error) => {
          const msg = error.name + error.message
          this.$alert(msg, '错误', { type: 'error' })
        }).finally(() => {
          this.loadGetESBJJ = false
        })
    },
    DownAMTracking(){
      this.loadGetESBJJ=true;
      axios({
        method: 'post',
        url: 'http://wms.xingyunyi.cn/api/TrackingMore/GetESBAM',
        // data: JSON.stringify(this.trackingMoreParamsDto),
        responseType: 'blob',
        timeout:600000,
        headers: { 'Content-Type': 'application/json', 'Token': getToken() }
      })
        .then((res) => {
          console.log(res)
          const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
          const fileName = Date.parse(new Date()) + 'AM轨迹.xlsx'
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
          } else {
            var link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = fileName
            link.click()
            // 释放内存
            window.URL.revokeObjectURL(link.href)
          }
        })
        .catch((error) => {
          const msg = error.name + error.message
          this.$alert(msg, '错误', { type: 'error' })
        }).finally(() => {
          this.loadGetESBJJ = false
        })
    },
    serarch(index){
      if(index>0)
      this.pagerDto.PageIndex=index
      if (this.timeRange2 && this.timeRange2.length > 0) {
        this.pagerDto._GrE_time = this.timeRange2[0]
        this.pagerDto._LeE_time = this.timeRange2[1]
      } else {
        this.pagerDto._GrE_time = ''
        this.pagerDto._LeE_time = ''
      }
      QueryPager(this.pagerDto).then(r=>{
        this.logs=r.Result;
        this.pagerDto.total = r.TotalCount;
      })
    },
    onSelection(s) {
      this.multipleSelection = s
      var numbers = []
      for (let i = 0; i < this.multipleSelection.length; i++) {
        numbers.push(this.multipleSelection[i].key)
      }
      this.keys = numbers.join(',')
    }
  }
}
</script>
<style scoped>
.esuibao {
  background-color: #f3f3f3;
  padding: 20px;
}

.esuibao .title {
  padding: 15px 20px;
  background-color: #fff;
}
</style>
