<script setup lang="ts">
import {computed, ref} from "vue";
import StockComposeTaskTypeFormatter from "@/plugin/formatter/StockComposeTaskTypeFormatter.ts";
import StockComposeTaskStatusFormatter from "@/plugin/formatter/StockComposeTaskStatusFormatter.ts";
import StockComposeStepStatusFormatter from "@/plugin/formatter/StockComposeStepStatusFormatter.ts";
import TrueFalseTagStyleFormatter from "@/plugin/formatter/TrueFalseTagStyleFormatter.ts";
import StringUtils from "@/utils/StringUtils.ts";
import StockComposeTaskApi from "@/api/stockComposeTask.ts";
import MessageUtils from "@/utils/MessageUtils.ts";
import {AppServeResponseCodeEnum} from "@/constant/enums/AppServeResponseCodeEnum.ts";
import type {AppServeResponse} from "@/interface/api/AppServeResponse.ts";
import type {ReporterTaskStatusReq} from "@/interface/page/stockTask/IReporterTaskStatusReq.ts";
import type {AppServeDataResponse} from "@/interface/api/AppServeDataResponse.ts";
import type {ICourseCalculateResult} from "@/interface/page/stockTask/ICourseCalculateResult.ts";

const modelValue = defineModel('modelValue', {required: true, default: false});
const props = defineProps(['formData']);
const emit = defineEmits(['reLoadingTableData']);
const close = () => {
  modelValue.value = false;
}
const formData = computed(() => props.formData);
const stockComposeTaskStatusFormatter = new StockComposeTaskStatusFormatter();
const stockComposeTaskTypeFormatter = new StockComposeTaskTypeFormatter();
const stockComposeStepStatusFormatter = new StockComposeStepStatusFormatter();
const trueFalseTagStyleFormatter = new TrueFalseTagStyleFormatter();
const uploadString = ref<string>("手动上报"); // 上报信息
const uploadDestination = ref<string>(""); // 上报的终点
const course = ref<string[]>([]);

// 完成任务
const completeTask = () => {
  MessageUtils.confirmMessageBox('确定完成任务？', '风险提示').then(() => {
    const loadingInstance = MessageUtils.loading();
    StockComposeTaskApi.completeTask(formData.value.taskId).then((res) => {
      const responseString = JSON.stringify(res.data);
      const response = JSON.parse(responseString) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('完成成功');
        emit('reLoadingTableData');
        close();
        return;
      }
      MessageUtils.errMessageBox(response.msg, '服务器信息');
    }).catch(() => {}).finally(() => {
      loadingInstance.close();
    })
  }).catch(() => {});
};
// 重做任务
const resetTask = () => {
  MessageUtils.confirmMessageBox('确定重做任务？', '风险提示').then(() => {
    const loadingInstance = MessageUtils.loading();
    StockComposeTaskApi.resetTask(formData.value.taskId).then((res) => {
      const responseString = JSON.stringify(res.data);
      const response = JSON.parse(responseString) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('重做成功');
        emit('reLoadingTableData');
        close();
        return;
      }
      MessageUtils.errMessageBox(response.msg, '服务器信息');
    }).catch(() => {}).finally(() => {
      loadingInstance.close();
    })
  }).catch(() => {});
};
// 取消任务
const cancelTask = () => {
  MessageUtils.confirmMessageBox('确定取消任务？', '风险提示').then(() => {
    const loadingInstance = MessageUtils.loading();
    StockComposeTaskApi.cancelTask(formData.value.taskId).then((res) => {
      const responseString = JSON.stringify(res.data);
      const response = JSON.parse(responseString) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('取消成功');
        emit('reLoadingTableData');
        close();
        return;
      }
      MessageUtils.errMessageBox(response.msg, '服务器信息');
    }).catch(() => {}).finally(() => {
      loadingInstance.close();
    })
  }).catch(() => {});
};
// 上报任务完成
const reportTaskComplete = () => {
  MessageUtils.confirmMessageBox('确定上报任务完成？', '风险提示').then(() => {
    const loadingInstance = MessageUtils.loading();
    const reportData: ReporterTaskStatusReq = {
      taskId: formData.value.taskId,
      message: uploadString.value,
      destination: uploadDestination.value
    };
    StockComposeTaskApi.reportTaskComplete(reportData).then((res) => {
      const responseString = JSON.stringify(res.data);
      const response = JSON.parse(responseString) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('上报成功');
        return;
      }
      MessageUtils.errMessageBox(response.msg, '服务器信息');
    }).catch(() => {}).finally(() => {
      loadingInstance.close();
    })
  }).catch(() => {});
};
// 上报任务取消
const reportTaskCancel = () => {
  MessageUtils.confirmMessageBox('确定上报任务取消？', '风险提示').then(() => {
    const loadingInstance = MessageUtils.loading();
    const reportData: ReporterTaskStatusReq = {
      taskId: formData.value.taskId,
      message: uploadString.value,
      destination: uploadDestination.value
    };
    StockComposeTaskApi.reportTaskCancel(reportData).then((res) => {
      const responseString = JSON.stringify(res.data);
      const response = JSON.parse(responseString) as AppServeResponse;
      if (response && response.code == AppServeResponseCodeEnum.SUCCESS) {
        MessageUtils.successMessage('上报成功');
        return;
      }
      MessageUtils.errMessageBox(response.msg, '服务器信息');
    }).catch(() => {}).finally(() => {
      loadingInstance.close();
    })
  }).catch(() => {});
};
// 计算路线
const calculateCourse = () => {
  const loadingInstance = MessageUtils.loading();
  course.value = [];
  StockComposeTaskApi.calculateCourse(formData.value.taskId).then((res) => {
    const responseString = JSON.stringify(res.data);
    const response = JSON.parse(responseString) as AppServeDataResponse<ICourseCalculateResult[]>;
    if (response && response.code == AppServeResponseCodeEnum.SUCCESS && response.data != null) {
      const calculateResults = response.data;
      course.value = calculateResults.map(item => item.location + '(' + item.locationType + ')');
      MessageUtils.successMessage('查询成功');
      return;
    }
    MessageUtils.errMessageBox(response.msg, '操作失败');
  }).catch(() => {}).finally(() => {
    loadingInstance.close();
  })
};

// 弹窗打开时
const open = () => {
  course.value = [];
};

</script>

<template>
  <div>
    <el-dialog :model-value="modelValue" title="组合式任务详细信息" @close="close" :close-on-click-modal="false" @open="open">
      <el-scrollbar style="height:50vh">
        <el-row>
          <el-col :span="12">
            <el-form :model="formData" label-position="right" label-width="120px" require-asterisk-position="right">
              <el-form-item label="任务ID:" required>
                <el-input v-model="formData.taskId" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务组:" required>
                <el-input v-model="formData.taskGroup" disabled></el-input>
              </el-form-item>
              <el-form-item label="上游任务号:" required>
                <el-input v-model="formData.upperTaskId" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务类型:" required>
                <el-select v-model="formData.taskType" disabled>
                  <el-option v-for="item in stockComposeTaskTypeFormatter.taskTypeTagStyle" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="载具编号:" required>
                <el-input v-model="formData.vehicleNo" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务状态:" required>
                <el-select v-model="formData.taskStatus" disabled>
                  <el-option v-for="item in stockComposeTaskStatusFormatter.taskStatusTagStyle" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="任务起点:" required>
                <el-input v-model="formData.origin" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务目的地:" required>
                <el-input v-model="formData.destination" disabled></el-input>
              </el-form-item>
              <el-form-item label="步骤状态:" required>
                <el-select v-model="formData.stepStatus" disabled>
                  <el-option v-for="item in stockComposeStepStatusFormatter.stepStatusTagStyle" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="优先级:" required>
                <el-input-number :max="9" :min="0" v-model="formData.priority" disabled></el-input-number>
              </el-form-item>
              <el-form-item label="载具尺寸:" required>
                <el-input-number :max="9" :min="0" v-model="formData.vehicleSize" disabled></el-input-number>
              </el-form-item>
              <el-form-item label="载具重量:" required>
                <el-input-number :max="9" :min="0" v-model="formData.weight" disabled></el-input-number>
              </el-form-item>
              <el-form-item label="是否可取消:" required>
                <el-select v-model="formData.canCancel" disabled>
                  <el-option v-for="item in trueFalseTagStyleFormatter.trueFalseTagStyle" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间:" required>
                <el-input v-model="formData.createTime" disabled></el-input>
              </el-form-item>
              <el-form-item label="上次更新时间:" required>
                <el-input v-model="formData.updateTime" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务开始时间:" required>
                <el-input v-model="formData.startTime" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务完成时间:" required>
                <el-input v-model="formData.completeTime" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务结束时间:" required>
                <el-input v-model="formData.endTime" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务来源:" required>
                <el-input v-model="formData.taskSource" disabled></el-input>
              </el-form-item>
              <el-form-item label="创建人:" required>
                <el-input v-model="formData.createPerson" disabled></el-input>
              </el-form-item>
              <el-form-item label="任务信息:" required>
                <el-input v-model="formData.taskMsg" disabled></el-input>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="11" :offset="1">
            <el-row v-if="!StringUtils.isNullOrEmpty(formData.upperTaskId)">
              <el-row>
                <div>上报附加信息：</div>
                <el-input v-model="uploadString"></el-input>
              </el-row>
              <el-row>
                <div>终点（仅上报完成有效）：</div>
                <el-input v-model="uploadDestination"></el-input>
              </el-row>
              <el-row style="margin-top: 10px">
                <el-button-group>
                  <el-button type="success" @click="reportTaskComplete">上报任务完成</el-button>
                  <el-button type="warning" @click="reportTaskCancel">上报任务取消</el-button>
                </el-button-group>
              </el-row>
              <el-row>
                <el-text type="warning">此处仅上报不会更新任务状态，点击下方【完成任务】或者【取消任务】按钮时将会自动上报并更新任务状态</el-text>
              </el-row>
            </el-row>
            <el-row v-if="course.length > 0">
              <el-row>
                <el-text type="primary" style="font-size: 1.2rem">模拟路径计算：</el-text>
              </el-row>
              <el-row v-for="(item, index) in course" :key="index">
                <el-text type="success">{{item + (index == course.length - 1 ? '' : '&nbsp;&nbsp;&nbsp;&nbsp;---->&nbsp;&nbsp;&nbsp;&nbsp;' )}}</el-text>
              </el-row>
            </el-row>
          </el-col>
        </el-row>
      </el-scrollbar>
      <template #footer>
        <el-button-group>
          <el-button type="info" @click="calculateCourse">模拟路径计算</el-button>
          <el-button type="success" @click="completeTask">完成任务</el-button>
          <el-button type="primary" @click="resetTask">重做任务</el-button>
          <el-button type="warning" @click="cancelTask">取消任务</el-button>
          <el-button type="danger" @click="close">关闭窗口</el-button>
        </el-button-group>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>