<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-divider content-position="left">问题件登记</el-divider>
        <div class="container-question-warp">
          <div class="itemGroup">
            <el-form @submit.native.prevent>
              <el-form-item>
                <el-select
                  v-model="questionType"
                  placeholder="请选择问题"
                  clearable
                  filterable
                  class="question-type"
                >
                  <el-option
                    v-for="item in questionList"
                    :key="item.Name"
                    :label="item.Name"
                    :value="item.Value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <div class="systemNo">
                  <el-input
                    type="textarea"
                    v-model="inputNumber"
                    :autosize="{ minRows: 18, maxRows: 38}"
                    autocomplete="off"
                    class="input-with-select inputNumber"
                    placeholder="请录入运单号，每行一个">
                  </el-input>
                  <!-- @change="inputNumberHander" -->
                  <span class="define-right">{{ currentRowNum }}/{{ maxRowNum }}</span>
                </div>
              </el-form-item>
              <div class="text-center">
                <el-button
                  type="success"
                  :loading="confirmLoading"
                  @click="confirmBatchOrderUnusualReason">
                  批量提交
                </el-button>
                <el-button
                  class="error-btn"
                  type="warning"
                  :loading="confirmLoading"
                  @click="hanleRefreshError">
                  错误重试
                </el-button>
              </div>
            </el-form>
          </div>
          <div class="batch-warp" style="width: 600px;">
            <el-table
              style="width: auto"
              :data="batchListSource"
              border
              :row-class-name="getRowClassName"
              :height="tableHeight"
            >
              <el-table-column label="运单号" prop="TrackingNumber" width="200" />
              <el-table-column label="处理类型" prop="QueryTypeName" width="200" />
              <el-table-column label="处理结果" prop="ResultMessage" />
              <el-table-column label="操作时间" prop="CreateTime" width="200" />
            </el-table>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script>

import { _setOrderUnusualReason } from '@/api/interceptOrder'
import { _getOrderQuestion } from '@/api/baseInfo'
import { defineThrottle, getCurrentDateTime } from '@/utils'
import axios from 'axios';
import { getToken } from '@/utils/auth';
export default {
  name: 'Question',
  data() {
    return {
      questionType: '',
      inputNumber: '',
      batchListSource: [],
      trackingNumber: '',
      dto: {},
      questionList: [],
      currentRowNum: 0,
      maxRowNum: 100,
      confirmLoading: false,
      orderUnusualReasonUrl: process.env.VUE_APP_BASE_API + '/InterceptOrder/SetOrderUnusualReason',
      tableHeight: 580,
      throttledResize: null,
    }
  },
  watch: {
    // 监听跟踪单号
    inputNumber (newValue, oldValue) {
      const rowNum = this.getRow()
      const maxRowNum = this.maxRowNum
      this.currentRowNum = rowNum === maxRowNum ? maxRowNum : rowNum
      if(rowNum > maxRowNum) {
        this.inputNumber = oldValue
      }
    }
  },
  created() {
    var that = this
    _getOrderQuestion().then(response => {
      that.questionList = response
    })
    this.createThrottledResize()
    window.addEventListener('resize', this.throttledResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.throttledResize)
  },
  deactivated() {
    window.removeEventListener('resize', this.throttledResize)
  },
  methods: {
    // 计算表格的高度
    getTableHeight: function() {
      const tableHeight = window.innerHeight - 225
      this.tableHeight = tableHeight <= 560 ? 580 : tableHeight
    },
    createThrottledResize() {
      this.getTableHeight()
      this.throttledResize = defineThrottle(this.getTableHeight, 1000); // 使用lodash的throttle方法，设置节流的时间间隔为500ms
    },
    getRowClassName(scoped) {
      // if (scoped.row.Result != '成功') { return 'errorRow' } else { return '' }
      if(scoped.row.ResultState === 500) { return 'errorRow' } else { return '' }
    },
    getOrderUnusualReason(rowData, rowIndex) {
      return new Promise((resolve) => {
        if(rowData) {
          // 初始化时间
          const createTime = getCurrentDateTime()
          this.$set(this.batchListSource[rowIndex], 'CreateTime', createTime);
          const currentIndex = this.batchListSource.findIndex((i) => i.id === rowData.id)
          const data = { TrackingNumber: rowData.TrackingNumber, UnusualReason: rowData.UnusualReason }
          axios({
            method: 'post',
            url: this.orderUnusualReasonUrl,
            data: data,
            headers: { 'Content-Type': 'application/json', Token: getToken() }
          }).then(res => {
            if(currentIndex >= 0) {
              this.$set(this.batchListSource[currentIndex], 'ResultMessage', '操作成功');
              this.$set(this.batchListSource[currentIndex], 'ResultState', 200);
            }
          }).catch(error => {
            const getErrorText = error.response.data.Message || error.response.data.message || error.response.data
            if(currentIndex >= 0) {
              this.$set(this.batchListSource[currentIndex], 'ResultMessage', getErrorText);
              this.$set(this.batchListSource[currentIndex], 'ResultState', 500);
            }
          }).finally(() => {
            if(currentIndex >= 0) {
              // 更新时间
              const createTime = getCurrentDateTime()
              this.$set(this.batchListSource[currentIndex], 'CreateTime', createTime);
              this.orderSortList()
              resolve(true)
            }
          });
        }
      })
    },
    inputNumberHander() {
      const that = this
      this.dto.TrackingNumber = this.inputNumber.trim()
      this.dto.UnusualReason = this.questionType
      _setOrderUnusualReason(this.dto)
        .then(response => {
          that.batchListSource.unshift({
            TrackingNumber: this.dto.TrackingNumber,
            QueryTypeName: this.getQuestionName(this.dto.questionType),
            Result: '成功',
            OperTime: this.nowDateFormat()
          })
          that.inputNumber = ''
        })
        .catch(response => {
          debugger
          that.batchListSource.unshift({
            TrackingNumber: this.dto.TrackingNumber,
            QueryTypeName: this.getQuestionName(this.dto.questionType),
            Result: '失败' + response,
            OperTime: this.nowDateFormat()
          })
          that.inputNumber = ''
        })
    },
    nowDateFormat: function() {
      var date = new Date()
      return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
    },
    getQuestionName(type) {
      for (var i = 0; i < this.questionList.length; i++) {
        if (this.questionList[i].Value == this.questionType) {
          return this.questionList[i].Name
        }
      }
    },
    // 获取当前跟踪单号文本框的行数
    getRow() {
      if(!this.inputNumber) return 0
      let row = 0
      const inputNumberList = this.inputNumber.split("\n")
      inputNumberList.forEach(item => {
        if (item.length === 0) {
          row += 1
        } else {
          row += Math.ceil(item.replace(/[\u0391-\uFFE5]/g,"aa").length / 50)
        }
      })
      return row
    },
    // 错误排序
    orderSortList() {
      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);
        }
      });
    },
    // 批量提交
    async confirmBatchOrderUnusualReason() {
      const that = this
      const questionType = that.questionType
      if(!questionType) {
        that.$message({
          type: 'warning',
          message: '请选择问题登记'
        })
        return
      }
      const systemNumbers = that.inputNumber.split("\n")
      const numbersList = systemNumbers.filter((item) => item)
      if(numbersList.length === 0) {
        that.$message({
          type: 'warning',
          message: '请输入运单号'
        })
        return
      }
      const list = []
      numbersList.forEach((order,index) => {
        if(order) {
          const numbers = order.trim()
          list.push({
            id: `${index}_order`,
            TrackingNumber: numbers,
            UnusualReason: questionType,
            QueryTypeName: that.getQuestionName(questionType),
            ResultMessage: '-'
          })
        }
      });
      that.confirmLoading = true
      that.batchListSource = list
      // 同步
      for await (const [rowIndex, rowData] of list.entries()) {
        if (rowData.TrackingNumber) {
          await that.getOrderUnusualReason(rowData, rowIndex)
        }
      }
      that.confirmLoading = false
    },
    // 错误重试
    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.getOrderUnusualReason(rowData, rowIndex)
        }
      }
      this.confirmLoading = false
    }
  }
}
</script>
<style>
    .appBtn{
      width:100px;
      height:100px;
    }
    .inputNumber input{
      height:50px!important;
      font-size: 32px!important;
      line-height: 50px!important;
    }
    .inputNumber {
      margin-right:10px;
    }

    .errorRow{
      background-color:#FFEEFF!important;
    }
    .container-question-warp {
      display: flex;
      width: 100%;
      overflow-y: scroll;
    }
    .container-question-warp .itemGroup{
      flex-basis: 560px;
      flex-shrink: 0;
      margin: 10px;
      border: 1px solid #D3D4D6;
      padding: 30px 10px;
    }
    .container-question-warp .itemGroup .systemNo {
      position: relative;
    }
    .container-question-warp .itemGroup .define-right {
      position: absolute;
      color: #909399;
      font-size: 12px;
      bottom: 0;
      right: 30px;
    }
    .container-question-warp .itemGroup .el-input__inner,
    .container-question-warp .itemGroup .el-textarea__inner {
      font-size: 18px;
    }
    .container-question-warp  .itemGroup .question-type {
      width: 100%;
    }
    .itemGroup .question-type .el-input__inner {
      height: 42px;
      background-color: #F5F7FA;
    }
    .question-type .el-input.is-focus .el-input__inner {
      border-color:#dcdfe6;
    }
    .container-question-warp .batch-warp {
      flex: 1;
      margin: 10px;
      border: 1px solid #D3D4D6;
    }
    .app-container {
      padding: 10px;
    }
    .app-container .el-card__body {
      padding: 10px;
    }
    .app-container .mr-b10 {
      margin-bottom: 10px;
    }
</style>
