<template>
  <div class="app-container">
    <div class="filter-container">
      <el-divider content-position="left">邮政单号提前上网</el-divider>
      <div class="postal-tracking-online">
        <div class="itemGroup">
          <el-form v-loading="loading" :model="paramsDto">
            <el-form-item label="转单单号" label-width="100px">
              <div class="systemNo">
                <el-input
                  type="textarea"
                  placeholder="请输入转单单号，每行一个"
                  v-model="paramsDto.systemNo"
                  :autosize="{ minRows: 18, maxRows: 200}"
                  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="success"
              :loading="confirmLoading"
              @click="confirmReapplyESBTracking">
              提 交
            </el-button>
          </div>
        </div>
        <div class="batch-warp">
          <div class="export-right">
            <el-button type="primary" icon="el-icon-upload2" :loading="exportLoading" @click="exportESBTracking">导出</el-button>
          </div>
          <vxe-table
            border
            ref="xTableReapplyESBTracking"
            :data="batchListSource"
            :row-config="{isHover: true}"
            :row-class-name="rowClassName"
            :header-row-style="{
              background: '#E6F7FF',
              borderRight: '1px solid #ccc',
            }"
            :scroll-y="{enabled: false}"
            :column-config="{ resizable: true }"
          >
            <vxe-column title="提交时间" field="CreateTime" :min-width="120" />
            <vxe-column title="转单单号" field="SystemNo" :min-width="200" />
            <vxe-column title="提示内容" field="ResultMessage" :min-width="180">
              <template #default="{ row }">
                <div v-show="row.ResultMessage !== '-'">
                  {{ row.ResultMessage }}
                </div>
                <el-button
                  type="text"
                  v-show="row.ResultMessage === '-'"
                  :loading="row.ResultMessage === '-'"
                />
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { _getTrackingMoreAddESB } from '@/api/order'
import { getCurrentDateTime } from '@/utils'
export default {
  name: 'PostalTrackingOnline',
  data: function() {
    return {
      loading: false,
      paramsDto: {
        systemNo: null,
      },
      confirmLoading: false,
      batchListSource: [],
      currentRowNum: 0,
      maxRowNum: 500,
      exportLoading: false
    }
  },
  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: {
    getReapplyESBTracking(rowData, rowIndex) {
      return new Promise((resolve) => {
        if(rowData.SystemNo) {
          // 初始化时间
          const createTime = getCurrentDateTime()
          this.$set(this.batchListSource[rowIndex], 'CreateTime', createTime);
          const currentIndex = this.batchListSource.findIndex((i) => i.id === rowData.id)
          _getTrackingMoreAddESB(rowData.SystemNo)
            .then((res) => {
            if(res && currentIndex >= 0) {
              this.$set(this.batchListSource, currentIndex, {
                id: `${rowIndex}_systemNo`,
                SystemNo: rowData.SystemNo,
                ResultMessage: '操作成功',
                ResultState: 200
              });
            } else {
              const msg = res.Error || res.error || '系统繁忙'
              this.$set(this.batchListSource[currentIndex], 'ResultMessage', msg);
              this.$set(this.batchListSource[currentIndex], 'ResultState', 500);
            }
          }).catch((error) => {
            if(currentIndex >= 0) {
              const msg = error.response ? (error.response.data.message || error.response.data.errors || error.response.data) : error
              this.$set(this.batchListSource[currentIndex], 'ResultMessage', msg);
              this.$set(this.batchListSource[currentIndex], 'ResultState', 500);
            }
          }).finally(() => {
            if(currentIndex >= 0) {
              // 更新时间
              const createTime = getCurrentDateTime()
              this.$set(this.batchListSource[currentIndex], 'CreateTime', createTime);
              this.channelsOrderSortList()
              resolve(true)
            }
            const isEvery = this.batchListSource.every(item => item.ResultMessage !== '-')
            if(isEvery) this.confirmLoading = false
          })
        }
      })
    },
    // 批量取消渠道订单
    async updateReapplyESBTracking(systemNoList) {
      const list = []
      systemNoList.forEach((order,index) => {
        if(order) {
          list.push({ id: `${index}_systemNo`, CreateTime: '-', SystemNo: order, Type: this.paramsDto.type, ResultMessage: '-' })
        }
      })
      this.batchListSource = list
      // 同步
      for await (const [rowIndex, rowData] of list.entries()) {
        if (rowData.SystemNo) {
          await this.getReapplyESBTracking(rowData, rowIndex)
        }
      }
      // 异步
      // list.forEach((rowData, rowIndex) => {
      //   if(rowData.SystemNo) {
      //     this.getReapplyESBTracking(rowData, rowIndex)
      //   }
      // })
    },
    // 批量提交
    confirmReapplyESBTracking() {
      if (!this.paramsDto.systemNo) {
        this.$message({
          type: 'warning',
          message: '请输入转单单号'
        })
        return
      }
      const systemNoes = this.paramsDto.systemNo.split("\n")
      const systemNoList = systemNoes.filter((item) => item)
      if(systemNoList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请输入转单单号'
        })
        return
      }
      this.confirmLoading = true
      this.updateReapplyESBTracking(systemNoList)
    },
    // 错误重试
    async hanleRefreshError() {
      const isEvery = this.batchListSource.every(item => item.ResultState === 200)
      if(isEvery) {
        this.$message({
          type: 'warning',
          message: '暂无系统转单单号重试'
        })
        return
      }
      this.confirmLoading = true
      // 同步
      for await (const [rowIndex, rowData] of this.batchListSource.entries()) {
        if (rowData.ResultState === 500) {
          await this.getReapplyESBTracking(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'
    },
    // 导出
    async exportESBTracking() {
      const currentDate = getCurrentDateTime('-')
      const filename = '邮政单号提前上网' + currentDate
      this.exportLoading = true
      await this.$refs.xTableReapplyESBTracking.exportData({ type: 'csv', filename })
      this.exportLoading = false
    }
  }
}
</script>

<style scoped>
.export-right {
  margin: 6px;
}
.postal-tracking-online {
  display: flex;
  overflow-y: scroll;
}
.postal-tracking-online .itemGroup{
  position: relative;
  height: 82vh;
  overflow: auto;
  flex-basis: 43%;
  flex-shrink: 0;
  margin: 10px;
  border: 1px solid #D3D4D6;
  padding: 48px 10px 0px 10px;
}
.postal-tracking-online .itemGroup .footer-btns {
  position: sticky;
  bottom: 0;
  padding-bottom: 30px;
  background-color: #ffffff;
}
.postal-tracking-online .itemGroup .systemNo {
  position: relative;
}
.postal-tracking-online .itemGroup .define-right {
  position: absolute;
  color: #909399;
  font-size: 12px;
  top: 0;
  right: 42px;
}
.postal-tracking-online .itemGroup .item-form {
  width: 95%;
}
.postal-tracking-online .batch-warp {
  flex: 1;
  margin: 10px;
  border: 1px solid #D3D4D6;
}
</style>
