<template>
  <div class="app-container">
    <div class="filter-container">
      <el-divider content-position="left"> 订单批量重计费 </el-divider>
      <div class="recharing-order-warp">
        <div class="itemGroup">
          <el-form v-loading="loading" :model="paramsDto">
            <el-form-item label="重算类型" label-width="100px">
              <el-select
                v-model="paramsDto.reCustomerComputeType"
                placeholder="重算类型"
                clearable
                filterable
              >
                <el-option
                  v-for="item in reCustomerComputeType"
                  :key="item.Value"
                  :label="item.Name"
                  :value="item.Value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="版本类型" label-width="100px">
              <el-select
                v-model="paramsDto.reComputeVerType"
                placeholder="版本类型"
                clearable
                filterable
              >
                <el-option
                  v-for="item in reComputeVerType"
                  :key="item.Value"
                  :label="item.Name"
                  :value="item.Value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="系统单号" label-width="100px">
              <div class="systemNo">
                <el-input
                  v-model="paramsDto.systemNo"
                  type="textarea"
                  placeholder="请输入单号，每行一个"
                  :autosize="{ minRows: 18, maxRows: 500 }"
                  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"
              :disabled="isBatchConfirm"
              @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
                  v-show="row.ResultMessage === '-'"
                  type="text"
                  :loading="row.ResultMessage === '-'"
                />
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";
import {
  GetReComputeVerType,
  GetReCustomerComputeNew,
  GetReCustomerComputeType,
} from "@/api/notification/notification";
import { getCurrentDateTime } from "@/utils/dateFormate";

export default defineComponent({
  name: "OrderBatchRecharging",
  data: function () {
    return {
      loading: false,
      paramsDto: {
        systemNo: null,
        reCustomerComputeType: null,
        reComputeVerType: null,
      },
      reComputeVerType: [] as Recordable[],
      reCustomerComputeType: [] as Recordable[],
      confirmLoading: false,
      batchListSource: [] as Recordable[],
      currentRowNum: 0,
      maxRowNum: 500,
    };
  },
  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;
      }
    },
  },
  computed: {
    isBatchConfirm() {
      // @ts-ignore
      return !this.paramsDto.reCustomerComputeType || !this.paramsDto.reComputeVerType || !this.paramsDto.systemNo
    }
  },
  created() {
    GetReCustomerComputeType().then((response) => {
      const results = response.data.data
      if (results) this.reCustomerComputeType = results;
    });
    GetReComputeVerType().then((response) => {
      const results = response.data.data
      if (results) this.reComputeVerType = results;
    });
  },
  methods: {
    getCancelOrder(rowData, rowIndex) {
      const type = this.paramsDto.reCustomerComputeType;
      const reComputeVerType = this.paramsDto.reComputeVerType;

      return new Promise((resolve) => {
        if (rowData.SystemNo) {
          // 初始化时间
          const createTime = getCurrentDateTime();
          this.batchListSource[rowIndex].CreateTime = createTime;
          const currentIndex = this.batchListSource.findIndex(
            (i) => i.id === rowData.id
          );
          GetReCustomerComputeNew({
            systemNo: rowData.SystemNo,
            reCustomerComputeType: type,
            reComputeVerType: reComputeVerType,
          })
            .then((res) => {
              const results = res.data.data
              if (results && results.length > 0 && currentIndex >= 0) {
                const currentObj = results[0];
                this.batchListSource[currentIndex] = currentObj;
              } else {
                this.batchListSource[currentIndex].ResultMessage = "操作成功";
                this.batchListSource[currentIndex].ResultState = 200;
              }
            })
            .catch((error) => {
              if (currentIndex >= 0) {
                const resultMessage = error.response.data.message || error
                this.batchListSource[currentIndex].ResultMessage = resultMessage;
                this.batchListSource[currentIndex].ResultState = 500;
              }
            })
            .finally(() => {
              if (currentIndex >= 0) {
                // 更新时间
                this.batchListSource[rowIndex].CreateTime = createTime;
                this.channelsOrderSortList();
                resolve(true);
              }
              const isEvery = this.batchListSource.every(
                (item) => item.ResultMessage !== "-"
              );
              if (isEvery) this.confirmLoading = false;
            });
        }
      });
    },
    // 批量取消渠道订单
    async updateBatchChannelOrder(systemNoList) {
      const list: Recordable[] = [];
      systemNoList.forEach((order, index) => {
        if (order) {
          list.push({
            id: `${index}_systemNo`,
            CreateTime: "-",
            SystemNo: order.trim(),
            ResultMessage: "-",
          });
        }
      });
      this.batchListSource = list;
      // 同步
      for await (const [rowIndex, rowData] of list.entries()) {
        if (rowData.SystemNo) {
          await this.getCancelOrder(rowData, rowIndex);
        }
      }
    },
    // 批量提交
    confirmBatchChannelOrder() {
      const systemNo = this.paramsDto.systemNo as unknown as string;
      if (!systemNo) {
        ElMessage({
          type: "warning",
          message: "请输入系统单号",
        });
        return;
      }
      const systemNoes = systemNo.split("\n");
      const systemNoList = systemNoes.filter((item) => item);
      if (systemNoList.length === 0) {
        ElMessage({
          type: "warning",
          message: "请输入系统单号",
        });
        return;
      }
      this.confirmLoading = true;
      this.updateBatchChannelOrder(systemNoList);
    },
    // 错误重试
    async hanleRefreshError() {
      const isEvery = this.batchListSource.every(
        (item) => item.ResultState === 200
      );
      if (isEvery) {
        ElMessage({
          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 {
          // 根据时间排序
          const CreateTimeB: any = new Date(b.CreateTime);
          const CreateTimeA: any = new Date(a.CreateTime);
          return CreateTimeB - CreateTimeA;
        }
      });
    },
    // 获取当前跟踪单号文本框的行数
    getRow() {
      const systemNo = this.paramsDto.systemNo as unknown as string;
      if (!systemNo) return 0;
      let row = 0;
      const systemNoList = 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 "text-red";
    },
  },
});
</script>

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