<template>
  <div class="app-container">
    <div class="filter-container">
      <el-divider content-position="left">变更17服务商</el-divider>
      <el-form v-loading="loading" :model="paramsDto" :rules="paramsRules" label-width="80px" ref="serviceProviderRef">
        <div class="seventeen-serviceProvider">
          <div class="itemGroup">
            <el-form-item label="旧17线路" prop="oldId">
              <el-select v-model="paramsDto.oldId" :filterable="true" :clearable="true" style="width: 98%;"
                :filter-method="filterMethod" @clear="clearMethod">
                <el-option v-for="item in filteredOptions" :key="item.key"
                  :label="`${item['_name_zh-cn']}-${item._country_iso}`" :value="String(item.key)">
                  <div class="tracking-flex">
                    <div>{{ item['_name_zh-cn'] }}</div>
                    <div>{{ item._country_iso }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="新17线路" prop="newId">
              <el-select v-model="paramsDto.newId" :filterable="true" :clearable="true" style="width: 98%;"
                :filter-method="filterMethod" @clear="clearMethod">
                <el-option v-for="item in filteredOptions" :key="item.key"
                  :label="`${item['_name_zh-cn']}-${item._country_iso}`" :value="String(item.key)">
                  <div class="tracking-flex">
                    <div>{{ item['_name_zh-cn'] }}</div>
                    <div>{{ item._country_iso }}</div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <div class="text-center footer-btns">
              <el-button style="width: 150px; line-height: 20px;" type="success" :loading="confirmLoading"
                @click="confirmBatchServiceProvider">
                提 交
              </el-button>
            </div>
          </div>
          <div class="batch-warp">
            <el-form-item label="运单号" prop="trackingNumbers">
              <div class="trackingNumbers">
                <el-input type="textarea" placeholder="请输入运单号，每行一个" v-model="paramsDto.trackingNumbers"
                  :autosize="{ minRows: 26, maxRows: 37 }" class="item-form" />
                <span class="define-right">{{ currentRowNum }}/{{ maxRowNum }}</span>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { _updateChange17TrackingInfo } from '@/api/order'
import { getCurrentDateTime } from '@/utils'
import axios from 'axios'
export default {
  name: 'SeventeenServiceProvider',
  data: function () {
    return {
      loading: false,
      paramsDto: {
        trackingNumbers: null,
        oldId: undefined,
        newId: undefined,
      },
      paramsRules: {
        trackingNumbers: [
          { required: true, message: '请输入运单号', trigger: 'blur' },
        ],
        newId: [
          { required: true, message: '请选择新17线路', trigger: 'change' }
        ],
        oldId: [
          { required: true, message: '请选择旧17线路', trigger: 'change' }
        ],
      },
      confirmLoading: false,
      batchListSource: [],
      currentRowNum: 0,
      maxRowNum: 1000,
      seventeenTrack: [],
      searchQuery: ''
    }
  },
  watch: {
    // 监听跟踪单号
    'paramsDto.trackingNumbers'(newValue, oldValue) {
      const rowNum = this.getRow()
      const maxRowNum = this.maxRowNum
      this.currentRowNum = rowNum === maxRowNum ? maxRowNum : rowNum
      if (rowNum > maxRowNum) {
        this.paramsDto.trackingNumbers = oldValue
      }
    }
  },
  computed: {
    filteredOptions() {
      if (!this.searchQuery) return this.seventeenTrack.slice(0, 260)
      return this.seventeenTrack.filter(item => {
        return item['_name_zh-cn'].includes(this.searchQuery);
      });
    }
  },
  created() {
    // 17Track跟踪列表
    axios.get('https://res.17track.net/asset/carrier/info/apicarrier.all.json').then((res) => {
      if (res.status === 200) {
        this.seventeenTrack = res.data
      }
    }).catch((error) => {
      this.$message({ type: 'error', message: error })
    })
  },
  methods: {
    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
            })
        }
      })
    },
    // 批量提交
    confirmBatchServiceProvider() {
      this.confirmLoading = true
      this.$refs.serviceProviderRef.validate((valid) => {
        if (valid) {
          const trackingNumbers = this.paramsDto.trackingNumbers.split("\n")
          const TrackingNumbers = trackingNumbers.filter((item) => item)
          _updateChange17TrackingInfo({ TrackingNumbers, oldId: this.paramsDto.oldId, newId: this.paramsDto.newId }).then(() => {
            this.$message({ type: 'success', message: '操作成功' })
          }).finally(() => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
          return false;
        }
      });
    },
    // 错误排序
    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.trackingNumbers) return 0
      let row = 0
      const systemNoList = this.paramsDto.trackingNumbers.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
    },
    filterMethod(value) {
      this.searchQuery = value;
    },
    clearMethod() {
      this.searchQuery = '';
    }
  }
}
</script>

<style scoped>
.seventeen-serviceProvider {
  display: flex;
  /* overflow-y: scroll; */
  padding: 15px 10px 0px 10px;
  border: 1px solid #D3D4D6;
}

.seventeen-serviceProvider .itemGroup {
  position: relative;
  flex-basis: 36%;
  min-width: 220px;
  /* flex: 1; */
  /* border: 1px solid #D3D4D6; */
}

.seventeen-serviceProvider .batch-warp {
  position: relative;
  height: 82vh;
  /* overflow: auto; */
  flex-basis: 64%;
  flex-shrink: 0;
  min-width: 460px;
}

.seventeen-serviceProvider .itemGroup .footer-btns {
  padding-top: 394px;
  /* position: sticky;
  bottom: 0;
  padding-bottom: 30px;
  background-color: #ffffff; */
}

.seventeen-serviceProvider .batch-warp .trackingNumbers {
  position: relative;
}

.seventeen-serviceProvider .batch-warp .define-right {
  position: absolute;
  color: #000000;
  font-size: 16px;
  font-weight: 700;
  top: 0px;
  right: 25px;
}

.seventeen-serviceProvider .batch-warp .item-form {
  width: 100%;
}

.tracking-flex {
  display: flex;
  justify-content: space-between;
}
</style>
