<template>
  <div class="app-container">
    <div class="filter-container">
      <el-divider content-position="left">收货确认</el-divider>
      <div class="confirmation-goods">
        <div class="itemGroup">
          <el-form :model="paramsDto" label-position="top">
            <el-form-item label="System single number:" label-width="100px">
              <div class="systemNo">
                <el-input v-model="paramsDto.systemNo" type="textarea"
                  placeholder="Please enter the single number, one per line." :autosize="{ minRows: 18, maxRows: 28 }"
                  class="item-form" />
                <span class="define-right">{{ currentRowNum }}/{{ maxRowNum }}</span>
              </div>
            </el-form-item>
          </el-form>
          <div class="text-center footer-btns">
            <el-button type="primary" :loading="confirmLoading" @click="confirmBatchChannelOrder">Batch
              submission</el-button>
            <el-button class="error-btn" type="info" :loading="confirmLoading" @click="hanleRefreshError">Error
              retry</el-button>
          </div>
        </div>
        <div class="batch-warp">
          <vxe-table border style="font-size: 16px;" empty-text="No data at present" :data="batchListSource"
            :row-config="{ isHover: true }" :row-class-name="rowClassName" :scroll-y="{ enabled: false }"
            :column-config="{ resizable: true }">
            <vxe-column title="Submission time" field="CreateTime" :width="165" />
            <vxe-column title="System single number" field="SystemNo" :min-width="200" />
            <vxe-column title="Prompt content" field="ResultMessage" :min-width="180">
              <template #default="{ row }">
                <div v-show="row.ResultMessage !== '-'">{{ row.ResultMessage }}</div>
                <el-button v-show="row.ResultMessage === '-'" type="text" :loading="row.ResultMessage === '-'" />
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { _getTrackingMoreAddESB } from '@/api/order'
import { getCurrentDateTime } from '@/utils'
import { getToken } from '@/utils/auth'
export default {
  name: 'ConfirmationGoods',
  data: function () {
    return {
      loading: false,
      paramsDto: {
        systemNo: null
      },
      confirmLoading: false,
      batchListSource: [],
      currentRowNum: 0,
      maxRowNum: 500
    }
  },
  watch: {
    // 监听跟踪单号
    'paramsDto.systemNo'(newValue, oldValue) {
      const rowNum = this.getRow()
      const maxRowNum = this.maxRowNum
      this.currentRowNum = rowNum === maxRowNum ? maxRowNum : rowNum
      if (rowNum > maxRowNum) {
        this.paramsDto.systemNo = oldValue
      }
    }
  },
  methods: {
    getCancelOrder(rowData, rowIndex) {
      const that = this
      return new Promise(resolve => {
        if (rowData.SystemNo) {
          // 初始化时间
          const createTime = getCurrentDateTime()
          that.$set(that.batchListSource[rowIndex], 'CreateTime', createTime)
          const currentIndex = that.batchListSource.findIndex(
            i => i.id === rowData.id
          )
          axios({
            method: 'post',
            url:
              'https://wms.xingyunyi.cn/api/order/confirm?number=' +
              rowData.SystemNo,
            data: {},
            headers: { token: getToken(), 'Content-Type': 'application/json' }
          })
            .then(res => {
              if (res.data.Success) {
                that.$set(
                  that.batchListSource[currentIndex],
                  'ResultMessage',
                  res.data.message
                )
                that.$set(
                  that.batchListSource[currentIndex],
                  'ResultState',
                  200
                )
              } else {
                that.$set(
                  that.batchListSource[currentIndex],
                  'ResultMessage',
                  res.data.message
                )
                that.$set(
                  that.batchListSource[currentIndex],
                  'ResultState',
                  500
                )
              }
            })
            .catch(error => {
              const msg =
                error.response.data.message ||
                error.response.data.errors ||
                error.response.data
              that.$set(
                that.batchListSource[currentIndex],
                'ResultMessage',
                msg
              )
              that.$set(that.batchListSource[currentIndex], 'ResultState', 500)
            })
            .finally(() => {
              // 更新时间
              const createTime = getCurrentDateTime()
              that.$set(
                this.batchListSource[currentIndex],
                'CreateTime',
                createTime
              )
              that.channelsOrderSortList()
              const isEvery = that.batchListSource.every(
                item => item.ResultMessage !== '-'
              )
              if (isEvery) that.confirmLoading = false
              resolve(true)
            })
        }
      })
    },
    // 批量确认系统单号
    async updateBatchChannelOrder(systemNoList) {
      const list = []
      systemNoList.forEach((order, index) => {
        if (order) {
          list.push({
            id: `${index}_systemNo`,
            CreateTime: '-',
            SystemNo: order,
            ResultMessage: '-'
          })
        }
      })
      this.batchListSource = list
      // 同步
      for await (const [rowIndex, rowData] of list.entries()) {
        if (rowData.SystemNo) {
          await this.getCancelOrder(rowData, rowIndex)
        }
      }
    },
    // 批量提交
    confirmBatchChannelOrder() {
      if (!this.paramsDto.systemNo) {
        this.$message({
          type: 'warning',
          message: 'Please enter the system number.'
        })
        return
      }
      const systemNoes = this.paramsDto.systemNo.split('\n')
      const systemNoList = systemNoes.filter(item => item)
      if (systemNoList.length === 0) {
        this.$message({
          type: 'warning',
          message: 'Please enter the system number.'
        })
        return
      }
      this.confirmLoading = true
      this.updateBatchChannelOrder(systemNoList)
    },
    // 错误重试
    async hanleRefreshError() {
      const isEvery = this.batchListSource.every(
        item => item.ResultState === 200
      )
      if (isEvery) {
        this.$message({
          type: 'warning',
          message: 'There is no system single number to retry at present.'
        })
        return
      }
      this.confirmLoading = true
      // 同步
      for await (const [rowIndex, rowData] of this.batchListSource.entries()) {
        if (rowData.ResultState === 500) {
          await this.getCancelOrder(rowData, rowIndex)
        }
      }
    },
    // 错误排序
    channelsOrderSortList() {
      this.batchListSource = this.batchListSource.sort((a, b) => {
        // 根据错误排序
        if (a.ResultState === 500 && b.ResultState === 200) {
          return -1
        } else if (a.ResultState === 200 && b.ResultState === 500) {
          return 1
        } else {
          // 根据时间排序
          return new Date(b.CreateTime) - new Date(a.CreateTime)
        }
      })
    },
    // 获取当前跟踪单号文本框的行数
    getRow() {
      if (!this.paramsDto.systemNo) return 0
      let row = 0
      const systemNoList = this.paramsDto.systemNo.split('\n')
      systemNoList.forEach(item => {
        if (item.length === 0) {
          row += 1
        } else {
          row += Math.ceil(item.replace(/[\u0391-\uFFE5]/g, 'aa').length / 50)
        }
      })
      return row
    },
    // 表格错误样式
    rowClassName({ row }) {
      if (row.ResultState === 500) return 'error-bg'
    }
  }
}
</script>

<style scoped>
.confirmation-goods {
  display: flex;
  overflow-y: auto;
  background-color: #ffffff;
}
.confirmation-goods .itemGroup {
  position: relative;
  height: 83vh;
  overflow: auto;
  flex-basis: 580px;
  flex-shrink: 0;
  margin: 10px;
  border: 1px solid #d3d4d6;
  padding: 6px 10px 0px 10px;
}
.confirmation-goods .itemGroup .footer-btns {
  position: sticky;
  bottom: 0;
  padding-bottom: 20px;
  background-color: #ffffff;
}
.confirmation-goods .itemGroup .systemNo {
  position: relative;
}
.confirmation-goods .itemGroup .define-right {
  position: absolute;
  color: #909399;
  font-size: 15px;
  top: 0px;
  right: 22px;
}
.confirmation-goods .itemGroup .item-form {
  width: 100%;
  font-size: 16px;
}
.confirmation-goods .itemGroup ::v-deep .el-form-item__label {
  font-size: 16px;
}
.confirmation-goods .batch-warp {
  flex: 1;
  margin: 10px;
  margin-left: 0;
  border: 1px solid #d3d4d6;
}
</style>
