<template>
  <div class="n-app-container">
    <el-card v-if="!showFull" shadow="never" style="margin-bottom:20px;">
      <el-tabs :value="'下单失败'" @tab-click="handleClick">
        <el-tab-pane name="下单中">
          <span slot="label">
            下单中 <el-badge :value="onCreateing" class="item" />
          </span>
        </el-tab-pane>
        <el-tab-pane name="下单失败">
          <span slot="label">
            下单失败 <el-badge :value="onError" class="item" />
          </span>
        </el-tab-pane>
        <el-tab-pane name="下单完成">
          <span slot="label">
            下单完成 <el-badge :value="onSuccuess" class="item" />
          </span>
        </el-tab-pane>
      </el-tabs>
      <el-form v-model="pagerDto" inline>
        <el-form-item>
          <el-tooltip v-model="numberInputVisible" 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="numberInputVisible = 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_TranferNumber"
              placeholder="转单号"
              clearable
              size="mini"
              @focus="openNumbersInputPannel"
            />
          </el-tooltip>
        </el-form-item>
        <el-form-item>
          <el-select v-model="pagerDto._Eq_IsFilter" clearable size="mini" placeholder="过滤无需要关注错误">
            <el-option :value="1" label="过滤无需要关注错误" />
            <el-option :value="0" label="显示全部" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="pagerDto._Eq_ShowExpress" clearable size="mini" placeholder="过滤无需要关注错误">
            <el-option :value="1" label="过滤快递" />
            <el-option :value="0" label="不过滤快递" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="pagerDto._Eq_ProblemHandling" clearable size="mini" placeholder="过滤已处理">
            <el-option :value="1" label="过滤" />
            <el-option :value="0" label="不过滤" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="block">
            <el-date-picker
              v-model="createTime"
              size="mini"
              type="daterange"
              range-separator="至"
              start-placeholder="创建开始日期"
              value-format="yyyy-MM-dd"
              end-placeholder="创建结束日期"
            />
          </div>
        </el-form-item>

        <el-form-item clearable>
          <el-select
            v-model="pagerDto._Eq_CreateOrderChannelId"
            size="mini"
            placeholder="下单渠道"
            clearable
            filterable
          >
            <el-option
              v-for="item in channels"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="pagerDto._Co_ErrorMessage"
            placeholder="包含错误"
            clearable
            size="mini"
          />
        </el-form-item>
        <el-form-item><el-button
          :loading="loading"
          type="primary"
          size="mini"
          @click="getLogs"
        >搜索</el-button></el-form-item></el-form>
    </el-card>
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <el-button size="mini" type="primary" :loading="retryLadding" @click="batchRetry">批量重试</el-button>
        <el-button v-clipboard:copy="transferNumers" v-clipboard:success="onCopy" v-clipboard:error="onErrorEvent" size="mini">复制单号</el-button>
        <div style="float:right">
          <el-link v-if="!showFull" @click="showFull=true;tableHeight=690">隐藏搜索</el-link>
          <el-link v-if="showFull" @click="showFull=false;tableHeight=530">显示搜索</el-link>
        </div>
      </div>
      <el-table :data="logs" :highlight-current-row="true" :select-on-indeterminate="true" width="100%" :height="tableHeight" @selection-change="onSelection">
        <el-table-column type="selection" :selectable="rowCanSelect" />
        <el-table-column
          prop="TranferNumber"
          label="转单号"
          width="200"
          fixed="left"
        >
          <template slot-scope="scope">
            <el-link v-if="scope.row.IsExecute == 1 && scope.row.IsSuccess == 0" type="primary" @click="clickTranferNumber(scope.row)">
              {{ scope.row.TranferNumber }}
            </el-link>
            <span v-if="scope.row.IsExecute == 1 && scope.row.IsSuccess == 1" type="primary" @click="clickTranferNumber(scope.row)">
              {{ scope.row.TranferNumber }}
            </span>
            <span v-if="scope.row.IsExecute == 0 && scope.row.IsSuccess == 0" type="primary" @click="clickTranferNumber(scope.row)">
              {{ scope.row.TranferNumber }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="pagerDto.IsSuccess==0"
          prop="ErrorMessage"
          label="错误信息"
          width="500"
          :show-overflow-tooltip="true"
          fixed="left"
        />
        <el-table-column
          v-if="pagerDto.IsSuccess==1"
          prop="TrackingNumber"
          label="跟踪单号"
          fixed="left"
        />
        <el-table-column label="下单渠道" prop="ChannelName" width="100" />
        <el-table-column label="派送渠道" prop="ProblemChannelName" width="150" />
        <el-table-column prop="CompanyName" label="客户" width="150" />
        <el-table-column prop="StrProblemGenerationTime" label="问题件产生时间" width="150" />
        <el-table-column prop="ErrorMessage" label="错误信息" />
        <el-table-column
          width="200"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-link v-if="scope.row.IsExecute == 1 && scope.row.IsSuccess == 0" icon="el-icon-edit" type="primary" @click="clickTranferNumber(scope.row)">编辑</el-link>
            <el-link v-if="scope.row.IsExecute == 1 && scope.row.IsSuccess == 0" icon="el-icon-refresh-right" type="success" @click="retry(scope.row)">重试</el-link>
            <el-dropdown @command="handleCommand">
              <el-link v-if="scope.row.IsExecute == 1 && scope.row.IsSuccess == 0" style="margin-left:5px" type="danger">转拦截<i class="el-icon-arrow-down el-icon--right" /></el-link>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{Id:scope.row.Id,ProblemHandlingType:12 }">偏远待退回</el-dropdown-item>
                <el-dropdown-item :command="{Id:scope.row.Id,ProblemHandlingType:17 }">地址异常待退回</el-dropdown-item>
                <el-dropdown-item :command="{Id:scope.row.Id,ProblemHandlingType:14 }">与客户核对邮编地址</el-dropdown-item>
                <el-dropdown-item :command="{Id:scope.row.Id,ProblemHandlingType:18 }">提交技术处理</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column></el-table>
      <el-pagination
        :page-sizes="[20,50,100, 200, 300, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        style="margin-top:10px"
        @current-change="getLogs"
        @size-change="sizeChange"
      />
    </el-card>

    <el-dialog title="修改地址" width="980px" :visible.sync="dialogOrderVisible" custom-class="changeAddress">
      <template slot="title">
        <h5 style="margin-left:20px;">修改地址</h5>
        <el-alert
          title="错误详情"
          type="error"
          :description="row.ErrorMessage"
          :closable="false"
        />
      </template>
      <el-form :model="row" label-width="80px">
        <el-row :gutter="9">
          <el-col :span="12">
            <el-form-item label="下单渠道">
              {{ row.ChannelName }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收件人">
              <el-input v-model="row.ReceiverName" placeholder="收件人" min="0" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国家">
              <div class="country-item">
                <el-input v-model="row.ReceiverCountryCode" placeholder="国家" min="0" autocomplete="off" />
                <el-checkbox v-model="row.SynchronizeOriginalCountry" size="medium" class="original-country">同步修改原单国家</el-checkbox>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="州名">
              <el-input v-model="row.ReceiverState" placeholder="州名" min="0" autocomplete="off" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="城市名">
              <el-input v-model="row.ReceiverCity" placeholder="城市名" min="0" autocomplete="off" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮编">
              <el-input v-model="row.ReceiverZipCode" placeholder="邮编" min="0" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话">
              <el-input v-model="row.ReceiverPhone" placeholder="电话" min="0" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门牌号">
              <el-input v-model="row.House" placeholder="门牌号" min="0" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地址">
              <el-input v-model="row.ReceiverStreet" placeholder="地址" min="0" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="winitOrderAdd(row.TranferNumber,row.ProblemChannelId)">winit单号补充</el-button>
        <el-button @click="frSearh">地址库匹配</el-button>
        <el-button @click="googleSearch">google地址查询</el-button>
        <el-button type="primary" @click="postOrder">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer
      title="法邮地址库"
      :visible.sync="frDrawer"
      :with-header="false"
    >
      <div style="padding:20px">
        <h4>
          按城市推荐
        </h4>

        <el-table :data="cityR" height="300" :border="true">
          <el-table-column prop="City" label="城市" />
          <el-table-column prop="ZipCode" label="邮编" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link type="primary" @click="setAddress(scope.row)">使用</el-link></template>
          </el-table-column>
        </el-table>

        <h4> 按邮编推荐 </h4>
        <el-table :data="zipR" height="300" :border="true">
          <el-table-column prop="State" label="州" />
          <el-table-column prop="City" label="城市" />
          <el-table-column prop="ZipCode" label="邮编" />
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-link type="primary" @click="setAddress(scope.row)">使用</el-link></template>
          </el-table-column>
        </el-table></div>
    </el-drawer>
  </div>
</template>
<script>
import { format } from '@/utils/multiInput'
import { getTransferLogList, retry, updateTranslog, _submitBatchRecover, _queryCounts, _submitBatchRetry, _problemTransfeLog, _updateWinitOrderAdd } from '@/api/transferLog'
import { _orderaddress } from '@/api/orderAddress'
import { _getAllPublic } from '@/api/baseInfo'
export default {
  name: 'TransferLog',
  data: function() {
    return {
      transferNumers: '',
      retryLadding: false,
      showFull: false,
      tableHeight: 530,
      zipR: [],
      cityR: [],
      frDrawer: false,
      showMap: false,
      onCreateing: 0,
      onError: 0,
      onSuccuess: 0,
      returnLoading: false,
      multipleSelection: [],
      dialogOrderVisible: false,
      numberInputVisible: false,
      inputNumbers: '',
      inputMultiCodes: '',
      logs: [],
      loading: false,
      googleUrl: '',
      channels: [],
      createTime: [],
      lastExecuteTime: [],
      row: {},
      pagerDto: {
        _Eq_IsFilter: 1,
        _In_TranferNumber: null,
        _Eq_IsSuccess: 0,
        _Eq_IsExecute: 1,
        _Eq_ShowExpress: 1,
        _Eq_ProblemHandling: 1,
        _GrE_ProblemGenerationTime: '',
        _LeE_ProblemGenerationTime: '',
        _GrE_LastExecuteTime: '',
        _LeE_LastExecuteTime: '',
        QuerySort: [{ Field: 'Id', IsDesc: false }],
        keyword: null,
        PageIndex: 1,
        PageSize: 20,
        total: 0
      }
    }
  },
  created() {
    var date = new Date()
    this.createTime = ['2023-03-01', this.DateFormat(date, 'yyyy-MM-dd')]
    this.getLogs()
    _getAllPublic().then((resp) => {
      this.channels = resp
    })
  },
  methods: {
    winitOrderAdd(tran, ProblemChannelId) {
      this.$prompt('补充winitOrderNo').then(r => {
        _updateWinitOrderAdd({ 'TranferNumber': tran, 'TrackingNumber': r.value, 'ProblemChannelId': ProblemChannelId }).then(r => {
          this.$message({ type: 'success', message: '补充成功' })
        })
      })
    },
    handleCommand(dto) {
      var that = this
      _problemTransfeLog(dto).then(r => {
        that.$message({ type: 'success', message: '复制成功' })
        this.getLogs()
      })
    },
    sizeChange(r) {
      this.pagerDto.PageSize = r
      this.getLogs()
    },
    onCopy() {
      this.$message({ type: 'success', message: '复制成功' })
    },
    onErrorEvent() {
      this.$message({ type: 'warning', message: '复制失败' })
    },
    setAddress(r) {
      if (r.State) {
        this.row.ReceiverState = r.State
      }
      this.row.ReceiverZipCode = r.ZipCode
      this.row.ReceiverCity = r.City
    },
    frSearh() {
      var that = this
      _orderaddress({ CountryCode: this.row.ReceiverCountryCode, OrderAddress: { City: this.row.ReceiverCity, ZipCode: this.row.ReceiverZipCode
      }}).then(response => {
        debugger
        that.zipR = response.ZipCodeRecommendedAddress
        that.cityR = response.CityRecommendedAddress
        that.frDrawer = true
      })
    },
    googleSearch() {
      this.showMap = true
      var baseUrl = 'https://www.google.com/maps/place/'
      baseUrl += encodeURI(this.row.ReceiverStreet + ' ' + (this.row.House ? this.row.House : '') + ' ' + this.row.ReceiverCity + ' ' + this.row.ReceiverZipCode)
      if (this.googleUrl != baseUrl) { this.googleUrl = baseUrl }
      window.open(baseUrl)
    },
    DateFormat(d, format) {
      var date = {
        'M+': d.getMonth() + 1,
        'd+': d.getDate(),
        'h+': d.getHours(),
        'm+': d.getMinutes(),
        's+': d.getSeconds(),
        'q+': Math.floor((d.getMonth() + 3) / 3),
        'S+': d.getMilliseconds()
      }
      if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
      }
      for (var k in date) {
        if (new RegExp('(' + k + ')').test(format)) {
          format = format.replace(RegExp.$1, RegExp.$1.length == 1
            ? date[k] : ('00' + date[k]).substr(('' + date[k]).length))
        }
      }
      return format
    },
    handleClick(tab, event) {
      if (tab.index == 1) {
        this.pagerDto._Eq_IsSuccess = 0
        this.pagerDto._Eq_IsExecute = 1
      } else if (tab.index == 0) {
        this.pagerDto._Eq_IsSuccess = 0
        this.pagerDto._Eq_IsExecute = 0
      } else if (tab.index == 2) {
        this.pagerDto._Eq_IsSuccess = 1
        this.pagerDto._Eq_IsExecute = 1
      }
      this.getLogs()
    },
    queryCounts() {
      _queryCounts(this.pagerDto).then(response => {
        for (var i = 0; i < response.length; i++) {
          if (response[i].Key == 0) {
            this.onCreateing = response[i].Value
          } else if (response[i].Key == 1) {
            this.onError = response[i].Value
          } else if (response[i].Key == 2) {
            this.onSuccuess = response[i].Value
          }
        }
      })
    },
    onSelection(s) {
      this.multipleSelection = s
      var TranferNumbers = []
      for (let i = 0; i < this.multipleSelection.length; i++) {
        TranferNumbers.push(this.multipleSelection[i].TranferNumber)
      }
      this.transferNumers = TranferNumbers.join('\r\n')
    },
    rowCanSelect(row) {
      return row.IsExecute == 1 && row.IsSuccess == 0
    },
    postOrder() {
      var _this = this
      updateTranslog(this.row).then(x => {
        this.dialogOrderVisible = false
        this.$message({
          showClose: true,
          message: '修改成功'
        })
        _this.getLogs()
      })
    },
    submitBatchRecover() {
      var that = this
      this.$prompt('退件后不可恢复, 是否继续?', '提示', {
        type: 'warning'
      }).then((value) => {
        var tranferNumber = []
        for (let i = 0; i < that.multipleSelection.length; i++) {
          tranferNumber.push(that.multipleSelection[i].TranferNumber)
        }
        this.returnLoading = true
        _submitBatchRecover({ TranferNumbers: tranferNumber, Remark: value.value }).then(response => {
          this.getLogs()
          this.returnLoading = false
        })
      })
    },
    batchRetry() {
      var that = this
      var id = []
      for (let i = 0; i < that.multipleSelection.length; i++) {
        id.push(that.multipleSelection[i].Id)
      }
      this.retryLadding = true
      _submitBatchRetry({ Ids: id }).then(response => {
        this.getLogs()
        this.retryLadding = false
      })
    },
    openNumbersInputPannel() {
      const str = format(this.pagerDto._In_TranferNumber, '\n')
      this.inputMultiCodes = str
      this.numberInputVisible = true
    },
    confirmMultiCodes() {
      const inputs = this.inputMultiCodes
      const str = format(inputs, ',')
      this.pagerDto._In_TranferNumber = str
      this.inputMultiCodes = ''
      this.numberInputVisible = false
    },
    retry(item) {
      const _this = this
      const tranferNumber = item.TranferNumber
      retry(tranferNumber).then(function(resp) {
        if (resp.Success == true) {
          item.IsExecute = false
          item.IsSuccess = false
          item.ErrorMesssage = null
          _this.getLogs()
        } else {
          const msg = resp.message
          _this.$message({
            message: msg,
            type: 'warning'
          })
        }
      })
    },
    getLogs(pageIndex) {
      const _this = this
      this.pagerSerach(pageIndex)
      this.loading = true
      const param = this.pagerDto

      this.queryCounts()
      getTransferLogList(param)
        .then(function(resp) {
          _this.logs = resp.Result
          _this.pagerDto.total = resp.TotalCount
        })
        .finally(function() {
          _this.loading = false
        })
    },
    pagerSerach(pageIndex) {
      if (this.createTime && this.createTime.length > 0) {
        this.pagerDto._GrE_ProblemGenerationTime = this.createTime[0]
        this.pagerDto._LeE_ProblemGenerationTime = this.createTime[1]
      } else {
        this.pagerDto._GrE_ProblemGenerationTime = ''
        this.pagerDto._LeE_ProblemGenerationTime = ''
      }

      if (this.lastExecuteTime && this.lastExecuteTime.length > 0) {
        this.pagerDto._GrE_LastExecuteTime = this.lastExecuteTime[0]
        this.pagerDto._LeE_LastExecuteTime = this.lastExecuteTime[1]
      } else {
        this.pagerDto._GrE_LastExecuteTime = ''
        this.pagerDto._LeE_LastExecuteTime = ''
      }

      if (pageIndex && pageIndex > 0) {
        this.pagerDto.PageIndex = pageIndex
      }
    },
    clickTranferNumber(row) {
      this.row = row;
      this.dialogOrderVisible = true;
      if (row.hasOwnProperty('SynchronizeOriginalCountry')) {
        this.$set(this.row, 'SynchronizeOriginalCountry', row.SynchronizeOriginalCountry)
      } else {
        this.$set(this.row, 'SynchronizeOriginalCountry', true)
      }
    }
  }
}
</script>
<style  scoped>
.country-item {
  display: flex;
}
.country-item .original-country {
  margin-left: 14px;
  font-weight: bold;
  color: #606266;
}
.country-item .original-country ::v-deep .el-checkbox__inner {
  width: 16px;
  height: 16px;
  border: 1px solid #606266;
}
.country-item .original-country ::v-deep .el-checkbox__inner::after {
  top: 2px;
  left: 5px;
}
.country-item .original-country ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner {
  border-color: #1890ff;
}
.el-alert{padding:16px; font-size: 14px; line-height: 18px;}
.el-alert p{font-size: 14px;}
 /* .el-form-item{margin-bottom: 0;} */
/* .bar{ background-color: #ffffff;margin:20px;padding: 20px;} */
</style>
