<template>
  <div class="app-container">
    <div class="filter-container">
      <el-divider content-position="left">计费渠道更换</el-divider>
      <div class="channel-change-warp">
        <div class="itemGroup">
          <el-form ref="paramsFormRef" label-width="120px" :model="paramsDto" :rules="paramsRules">
            <el-form-item label="跟踪单号" prop="tracking">
              <!-- <el-input v-model="paramsDto.tracking" placeholder="跟踪单号" class="item-form" /> -->
              <div class="tracking">
                <el-input
                  type="textarea"
                  placeholder="请输入单号，每行一个"
                  v-model="paramsDto.tracking"
                  :autosize="{ minRows: 5, maxRows: 100}"
                  class="item-form"
                >
                </el-input>
                <span class="define-right">{{ currentRowNum }}/{{ maxRowNum }}</span>
              </div>
            </el-form-item>
            <el-form-item label="目标下单渠道" prop="createChannelId">
              <el-select
                v-model="paramsDto.createChannelId"
                placeholder="目标下单渠道"
                clearable
                filterable
                class="item-form"
              >
                <el-option
                  v-for="(item,index) in channels"
                  :key="`${item.Id}_${index}`"
                  :label="item.Name"
                  :value="item.Id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="paramsDto.remark" placeholder="备注" class="item-form" />
            </el-form-item>
            <el-form-item>
              <!-- <el-button type="primary" @click="confirmChannel" :loading="confirmLoading">确定更换</el-button> -->
              <el-button type="primary" @click="confirmBatchChannel" :loading="confirmLoading">提交</el-button>
            </el-form-item>
          </el-form>
        </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',
            }"
            :column-config="{ resizable: true }"
          >
            <vxe-column title="提交时间" field="CreateTime" :min-width="120" />
            <vxe-column title="单号" field="Tracking" :min-width="200" />
            <vxe-column title="提示内容" field="Message" :min-width="130" />
          </vxe-table>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { _getChannel } from '@/api/baseInfo';
import { _ChangerOrderCreateChannelId } from '@/api/transfer/channelChangeEndService'
import { getCurrentDateTime } from '@/utils/index';

export default{
  name: 'ChannelChangeEndService',
  data() {
    return {
      paramsDto: {
        tracking: '',
        createChannelId: undefined,
        remark: ''
      },
      channels: [],
      paramsRules: {
        tracking: [{ required: true, message: '请输入跟踪单号', trigger: 'blur' }],
        createChannelId: [{ required: true, message: '请选择目标下单渠道', trigger: 'change' }]
      },
      confirmLoading: false,
      batchListSource: [],
      currentRowNum: 0,
      maxRowNum: 100
    }
  },
  watch: {
    // 监听跟踪单号
    'paramsDto.tracking'(newValue, oldValue) {
      const rowNum = this.getRow()
      const maxRowNum = this.maxRowNum
      this.currentRowNum = rowNum === maxRowNum ? maxRowNum : rowNum
      if(rowNum > maxRowNum) {
        this.paramsDto.tracking = oldValue
      }
    }
  },
  created() {
    _getChannel().then((resp) => {
      this.channels = resp
    })
  },
  methods: {
    // 确定更换渠道
    confirmChannel() {
      this.confirmLoading = true
      this.$refs.paramsFormRef.validate((valid) => {
        if (valid) {
          _ChangerOrderCreateChannelId(this.paramsDto).then(() => {
            this.$message({ type: 'success', message: '操作成功' })
          }).finally(() => {
            this.confirmLoading = false
          })
        } else {
          this.confirmLoading = false
          return false;
        }
      });
    },
    // 模拟数据
    getTestData(isRes) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(isRes)
        },2000)
      })
    },
    channelsSortList() {
      // this.batchListSource = this.batchListSource.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
      this.batchListSource = this.batchListSource.sort((a, b) => {
        // 根据错误排序
        if (a.Error && !b.Error) {
          return -1;
        } else if (!a.Error && b.Error) {
          return 1;
        } else {
          // 根据时间排序
          return new Date(a.CreateTime) - new Date(b.CreateTime);
        }
      });
    },
    // 批量提交计费渠道信息
    async updateBatchChannel() {
      const trackingList = this.paramsDto.tracking.split("\n")
      // console.log(trackingList,":this.paramsDto.tracking");
      const list = []
      trackingList.forEach((order,index) => {
        if(order) {
          list.push({ id: `${index}_tracking`, CreateTime: '-', Tracking: order, Message: '' })
        }
      })
      this.batchListSource = list
      const { createChannelId, remark } = this.paramsDto
      list.forEach((rowData, rowIndex) => {
        // 初始化时间
        const createTime = getCurrentDateTime()
        this.$set(this.batchListSource[rowIndex], 'CreateTime', createTime);
        _ChangerOrderCreateChannelId({ createChannelId, remark, tracking: rowData.Tracking })
          .then((res) => {
          const index = this.batchListSource.findIndex((i) => i.id === rowData.id)
          if(index >= 0) this.$set(this.batchListSource[index], 'Message', '成功');
        }).catch((error) => {
          const index = this.batchListSource.findIndex((i) => i.id === rowData.id)
          if(index >= 0) {
            this.$set(this.batchListSource[index], 'Message', error);
            this.$set(this.batchListSource[index], 'Error', !!error);
          }
        }).finally(() => {
          const index = this.batchListSource.findIndex((i) => i.id === rowData.id)
          if(index >= 0) {
            // 更新时间
            const createTime = getCurrentDateTime()
            this.$set(this.batchListSource[index], 'CreateTime', createTime);
            this.channelsSortList()
          }
          if(list.length === (rowIndex + 1)) this.confirmLoading = false
        })
      })
      // const res = await this.getTestData(item.Tracking == '333')
      // const index = this.batchListSource.findIndex((i) => i.id === item.id)
      // if(index >= 0) {
      //   const createTime = getCurrentDateTime()
      //   this.$set(this.batchListSource[index], 'CreateTime', createTime);
      //   this.$set(this.batchListSource[index], 'Error', res);
      //   this.channelsSortList()
      // }
    },
    confirmBatchChannel() {
      this.confirmLoading = true
      this.$refs.paramsFormRef.validate((valid) => {
        if (valid) {
          this.updateBatchChannel()
        } else {
          this.confirmLoading = false
          return false;
        }
      });
    },
    // 获取当前跟踪单号文本框的行数
    getRow() {
      if(!this.paramsDto.tracking) return 0
      let row = 0
      const trackingList = this.paramsDto.tracking.split("\n")
      trackingList.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.Error) return 'error-bg'
    }
  }
}
</script>
<style scoped>
.channel-change-warp {
  display: flex;
  overflow-y: scroll;
}
.channel-change-warp .itemGroup{
  flex-basis: 43%;
  flex-shrink: 0;
  margin: 10px;
  border: 1px solid #ebebeb;
  padding: 30px;
}
.itemGroup .tracking {
  position: relative;
}
.itemGroup .define-right {
  position: absolute;
  color: #909399;
  font-size: 12px;
  bottom: 0;
  right: 30px;
}
.channel-change-warp .itemGroup .item-form {
  width: 95%;
}
.channel-change-warp .batch-warp {
  flex: 1;
  margin: 10px;
  border: 1px solid #ebebeb;
}
</style>
