<template>
  <Navbar title="调度任务" :is-go-back="false" />
  <div>
    <a-form :colon="false" :label-col="labelStyle">
      <a-row :gutter="[8, 14]" justify="space-start">
        <a-form-item label="任务类型" class="horizontal-form-item">
          <a-select
            v-model:value="formData.workCategory" class="w-full" :options="workTypes" allow-clear
            placeholder="请选择任务类型" @change="searchDatas"
          />
        </a-form-item>
        <a-form-item label="仓库" class="horizontal-form-item">
          <a-select
            v-model:value="formData.warehouseId" class="w-full" :options="warehouseOptions" allow-clear
            placeholder="请选择仓库" @change="searchDatas"
          />
        </a-form-item>
        <a-form-item label="起始货位编号" class="horizontal-form-item">
          <a-input
            v-model:value="formData.positionBeginNo" class="w-full" placeholder="请输入起始货位编号"
            @press-enter="searchDatas"
          />
        </a-form-item>
        <a-form-item label="终点货位编号" class="horizontal-form-item">
          <a-input
            v-model:value="formData.positionEndNo" class="w-full" placeholder="请输入起始货位编号"
            @press-enter="searchDatas"
          />
        </a-form-item>
        <a-form-item label="执行状态" class="horizontal-form-item">
          <a-select
            v-model:value="formData.executeStatus" class="w-full" :options="executeStatus" allow-clear
            placeholder="请选择执行状态" @change="searchDatas"
          />
        </a-form-item>
        <a-form-item label="AGV编号" class="horizontal-form-item">
          <a-input v-model:value="formData.agvNo" class="w-full" placeholder="请输入AGV编号" @press-enter="searchDatas" />
        </a-form-item>
        <a-form-item label="是否成功" class="horizontal-form-item">
          <a-select
            v-model:value="formData.success" class="w-full" :options="successTypes" allow-clear
            placeholder="请选择是否成功" @change="searchDatas"
          />
        </a-form-item>
        <a-form-item label="" class="horizontal-form-item">
          <a-space>
            <a-button danger @click="clearFilter">清空</a-button>
            <a-button type="primary" @click="searchDatas">查询</a-button>
          </a-space>
        </a-form-item>
      </a-row>
    </a-form>

    <CommonTable
      ref="commonTableRef" :columns="columns" :data-source="taskList" :total="totalSize" :is-select="false" :extra-height="90"
      @get-pager="getPageParams"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'index'">
          {{ index + 1 }}
        </template>
        <template v-if="column.dataIndex === 'documentNo'">
          <a-button type="link" @click="openWindow(record)">{{ record.documentNo }}</a-button>
        </template>
        <template v-if="column.dataIndex === 'success'">
          <a-tag v-if="record.success === true" color="green">成功</a-tag>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a-tag v-if="record.executeStatus === '已完成'" color="green">已完成</a-tag>
          <a-button v-if="record.executeStatus === '执行中'" type="link" danger @click="cancelTask(record)">取消任务</a-button>
          <a-button v-if="record.executeStatus === '未开始'" type="link" @click="executeTask(record)">
            执行
          </a-button>
        </template>
      </template>
    </CommonTable>
  </div>
  <Loading v-if="loading" />
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Common from '../common/Common';
import { Uuid } from 'pc-component-v3';
import { message } from 'ant-design-vue';
import CommonTable from '../common/CommonTable.vue';
import { taskColumns, workOptions, executeOptions, successOptions } from '../common/transferTask';

const loading = ref(false);
const commonTableRef = ref(null);

const labelStyle = { style: { width: '90px' } };

const columns = ref(taskColumns);
const taskList = ref([]);

const formData = ref({
  workCategory: null,
  positionBeginNo: null,
  positionEndNo: null,
  executeStatus: null,
  agvNo: null,
  success: null,
  warehouseId: null,
});

const totalSize = ref(0);
const pagination = ref({
  start: 1,
  length: 20,
});

const workTypes = ref(workOptions);
const successTypes = ref(successOptions);
const executeStatus = ref(executeOptions);
const warehouseOptions = ref([]);

// 获取分页参数后查询
const getPageParams = (page, pageSize) => {
  pagination.value.start = page;
  pagination.value.length = pageSize;
  getTableDatas();
};

// 执行任务
const executeTask = record => {
  executeTaskById(record.schedulingTasksId);
};

// 执行任务
const cancelTask = record => {
  cancelTaskById(record.schedulingTasksId);
};

// 打开窗口
const openWindow = record => {
  const url = Common.getHostPageBaseURL() + `#/desktop/window1/window-read/view/${record.windowNo}/0/${record.documentId}?currPage=1&currIndex=1&totalCount=1&uuid=${Uuid.createUUID()}`;
  window.open(url,'_blank');
};

// 条件变化查询
const searchDatas = () => {
  commonTableRef.value.backFirstPage();
};

// 清空条件
const clearFilter = () => {
  formData.value = {
    workCategory: null,
    positionBeginNo: null,
    positionEndNo: null,
    executeStatus: null,
    agvNo: null,
    success: null,
    warehouseId: null,
  };
  searchDatas();
};

const getWarehouseOptions = () => {
  $.ajax({
    url: Common.getApiURL('WarehouseResource/queryUserManageWarehouse'),
    type: 'get',
    dataType: 'json',
    beforeSend: function (request) {
      Common.addTokenToRequest(request);
    },
    success: function (res) {
      if (res && res.length > 0) {
        warehouseOptions.value = res.map(item => ({
          label: item.name,
          value: item.id,
        }));
      } else {
        warehouseOptions.value = [];
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      console.error(XMLHttpRequest, textStatus, errorThrown);
    },
  });
};

onMounted(() => {
  getWarehouseOptions();
  getTableDatas();
});

// 查询调度任务
const getTableDatas = () => {
  const start = (pagination.value.start - 1) * pagination.value.length;
  const params = {
    ...formData.value,
    ...pagination.value,
    start,
  };
  loading.value = true;
  $.ajax({
    url: Common.getApiURL('SchedulingTasksResource/querySchedulingTasks'),
    type: 'post',
    contentType: 'application/json',

    dataType: 'json',
    data: JSON.stringify(params),
    beforeSend: function (request) {
      Common.addTokenToRequest(request);
    },
    success: function ({ errorCode, errorMessage, datas, total }) {
      if (errorCode === 0) {
        if (datas && datas.length > 0) {
          taskList.value = datas;
          totalSize.value = total;
        } else {
          taskList.value = [];
          totalSize.value = 0;
        }
      } else {
        taskList.value = [];
        totalSize.value = 0;
        message.warning(errorMessage);
      }
      loading.value = false;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      Common.processException(XMLHttpRequest, textStatus, errorThrown);
      loading.value = false;
    },
  });
};

// 执行任务Api
const executeTaskById = id => {
  loading.value = true;
  $.ajax({
    type: 'get',
    url: Common.getApiURL(`SchedulingTasksResource/executeTaskById?schedulingTasksId=${id}`),
    beforeSend(request) {
      Common.addTokenToRequest(request);
    },
    success: function ({ errorCode, errorMessage }) {
      if (errorCode === 0) {
        searchDatas();
        message.success('执行成功！');
      } else {
        searchDatas();
        message.warning(errorMessage);
      }
      loading.value = false;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      loading.value = false;
      Common.processException(XMLHttpRequest, textStatus, errorThrown);
    },
  });

};
// 取消任务Api
const cancelTaskById = id => {
  loading.value = true;
  $.ajax({
    type: 'get',
    url: Common.getApiURL(`SchedulingTasksResource/cancelWorkById?schedulingTasksId=${id}`),
    beforeSend(request) {
      Common.addTokenToRequest(request);
    },
    success: function ({ errorCode, errorMessage }) {
      if (errorCode === 0) {
        searchDatas();
        message.success('取消成功！');
      } else {
        searchDatas();
        message.warning(errorMessage);
      }
      loading.value = false;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      loading.value = false;
      Common.processException(XMLHttpRequest, textStatus, errorThrown);
    },
  });
};
</script>

<style scoped>
.horizontal-form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.w-full {
  width: 230px;
}

:deep(.ant-form-item-label > label) {
  font-size: 14px !important;
  font-weight: 600 !important;
}

:deep(.ant-form-item) {
  margin-bottom: 0px !important;
  margin-right: 16px !important;
}
</style>