<template>
  <div class="app-container">
    <div class="filter-container">
      <el-divider content-position="left">重新申请ESB单号</el-divider>
      <div class="reapply-ESB-Tracking">
        <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: 1000}"
                  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">
            <div class="export-btn">
              <el-button type="primary" icon="el-icon-upload2" :loading="exportLoading" @click="exportESBTracking">导出</el-button>
            </div>
            <div>
              批量导入总数量：<span class="total">{{ countingNum.totalNum }}</span>
              , 导入失败数量：<span class="error">{{ countingNum.errorNum }}</span>
              , 导入成功数量：<span class="success">{{ countingNum.successNum }}</span>
            </div>
          </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="NewSystemNo" :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 { _getHomeReGetLabel } from '@/api/order'
import { getCurrentDateTime } from '@/utils'
export default {
  name: 'ReapplyESBTracking',
  data: function() {
    return {
      loading: false,
      paramsDto: {
        systemNo: null,
      },
      confirmLoading: false,
      batchListSource: [],
      currentRowNum: 0,
      maxRowNum: 1000,
      exportLoading: false,
      countingNum: {//汇总数量
        totalNum: 0,
        errorNum: 0,
        successNum: 0
      },
    }
  },
  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)
          _getHomeReGetLabel(rowData.SystemNo)
            .then((res) => {
            if(typeof res === 'string' && currentIndex >= 0) {
              this.$set(this.batchListSource, currentIndex, {
                id: `${rowIndex}_systemNo`,
                SystemNo: rowData.SystemNo,
                NewSystemNo: res,
                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
      this.countingNum.totalNum = list.length
      // 同步
      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);
        }
      });
      const errorList = this.batchListSource.filter(item => item.ResultState === 500)
      this.countingNum.errorNum = errorList.length
      const successList = this.batchListSource.filter(item => item.ResultState === 200)
      this.countingNum.successNum = successList.length
    },
    // 获取当前转运单号文本框的行数
    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 = '申请ESB单号' + currentDate
      this.exportLoading = true
      await this.$refs.xTableReapplyESBTracking.exportData({ type: 'csv', filename })
      this.exportLoading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.export-right {
  display: flex;
  margin: 6px;
  align-items: center;
  line-height: 1.3;
  font-size: 14px;
  font-weight: bold;
  color: #606266;
  .export-btn {
    margin-right: 10px;
  }
  .total {
    font-size: 17px;
    color: #1A73E8;
  }
  .error {
    font-size: 17px;
    color: red;
  }
  .success {
    font-size: 17px;
    color: #67C23A;
  }
}

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