<template>
  <div class="app-container">
    <div class="filter-container">
      <el-divider content-position="left">订单批量回退</el-divider>
      <div class="return-order-warp">
        <div class="itemGroup">
          <el-form v-loading="loading" :model="paramsDto">
            <el-form-item label="批量模式" label-width="100px">
              <el-select v-model="paramsDto.type" style="width: 95%;">
                <el-option label="退回待揽收状态" :value="1"></el-option>
                <el-option label="退回待转运状态" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <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="confirmBatchChannelOrder">
              批量提交
            </el-button>
            <el-button
              class="error-btn"
              type="primary"
              :loading="confirmLoading"
              @click="hanleRefreshError">
              错误重试
            </el-button>
          </div>
        </div>
        <div class="batch-warp">
          <vxe-table
            border
            :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 { RecoverOrderStatus } from '@/api/order'
import { getCurrentDateTime } from '@/utils'
export default {
  name: 'OrderBatchReturn',
  data: function() {
    return {
      loading: false,
      paramsDto: {
        type: 1,
        systemNo: null,
      },
      confirmLoading: false,
      batchListSource: [],
      currentRowNum: 0,
      maxRowNum: 1000
    }
  },
  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: {
    submit() {
      const systemNo = this.systemNo
      if (!systemNo) {
        this.$message({ message: '请填写系统单号', type: 'error' })
        return
      }

      const params = { systemNo }
      this.loading = true

      RecoverOrderStatus(params)
        .then((res) => {
          this.$message({ message: '删除成功', type: 'success' })
        })
        .finally(() => {
          this.loading = false
        })
    },
    getCancelOrder(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)
          RecoverOrderStatus({ Number: rowData.SystemNo, Type: rowData.Type })
            .then((res) => {
            if(res && res.length > 0 && currentIndex >= 0) {
              const currentObj = res[0]
              this.$set(this.batchListSource, currentIndex, { ...currentObj  });
            } else {
              this.$set(this.batchListSource[currentIndex], 'ResultMessage', '操作成功');
              this.$set(this.batchListSource[currentIndex], 'ResultState', 200);
            }
          }).catch((error) => {
            if(currentIndex >= 0) {
              this.$set(this.batchListSource[currentIndex], 'ResultMessage', error);
              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 updateBatchChannelOrder(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.getCancelOrder(rowData, rowIndex)
        }
      }
      // 异步
      // list.forEach((rowData, rowIndex) => {
      //   if(rowData.SystemNo) {
      //     this.getCancelOrder(rowData, rowIndex)
      //   }
      // })
    },
    // 批量提交
    confirmBatchChannelOrder() {
      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.updateBatchChannelOrder(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.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>
.return-order-warp {
  display: flex;
  overflow-y: scroll;
}
.return-order-warp .itemGroup{
  position: relative;
  height: 82vh;
  overflow: auto;
  flex-basis: 43%;
  flex-shrink: 0;
  margin: 10px;
  border: 1px solid #D3D4D6;
  padding: 30px 10px 0px 10px;
}
.return-order-warp .itemGroup .footer-btns {
  position: sticky;
  bottom: 0;
  padding-bottom: 30px;
  background-color: #ffffff;
}
.return-order-warp .itemGroup .systemNo {
  position: relative;
}
.return-order-warp .itemGroup .define-right {
  position: absolute;
  color: #909399;
  font-size: 12px;
  top: 0;
  right: 42px;
}
.return-order-warp .itemGroup .item-form {
  width: 95%;
}
.return-order-warp .batch-warp {
  flex: 1;
  margin: 10px;
  border: 1px solid #D3D4D6;
}
</style>
