<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef"  v-show="showSearch" label-width="80">
      <el-row >
        <el-col :span="6">
          <el-form-item label="任务编号" prop="taskNo">
            <el-input
              v-model="queryParams.taskNo"
              placeholder="请输入任务编号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
       <el-col :span="6">
          <el-form-item label="任务状态" prop="taskStatus">
            <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态">
              <el-option label="待执行" value="0" />
              <el-option label="执行中" value="1" />
              <el-option label="已完成" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物料编码" prop="mid">
            <el-input
              v-model="queryParams.mid"
              placeholder="请输入物料编码"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="起始位置" prop="sourceName">
            <el-input
              v-model="queryParams.sourceName"
              placeholder="请输入起始位置"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row >
        <el-col :span="6">
          <el-form-item label="创建时间" prop="rcptim">
            <el-date-picker
              v-model="rcptim"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY/MM/DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="任务详情" prop="taskDtl">
            <el-input
              v-model="queryParams.taskDtl"
              placeholder="请输入任务详情"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="任务类型" prop="taskType">
            <el-select v-model="queryParams.taskType" placeholder="请选择任务类型">
              <el-option label="上架" value="0" />
              <el-option label="下架" value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
     
      
      
      
      <!-- <el-form-item label="操作员" prop="operator">
        <el-input
          v-model="queryParams.operator"
          placeholder="请输入操作员"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['wisdom:dispatch:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wisdom:dispatch:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wisdom:dispatch:remove']"
        >删除</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['wisdom:dispatch:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" show-overflow-tooltip @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
     
      <el-table-column label="任务编号" align="center" prop="taskNo" width="180"/>
      <!-- <el-table-column label="任务详情" align="center" prop="taskDtl" /> -->
      <el-table-column label="任务类型" align="center" prop="taskType" >
        <template #default="scope">
          <span>{{ taskTypeFun(scope.row.taskType)  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调度类型" align="center" prop="dispatchMode" >
        <template #default="scope">
          <span>{{ dispatchModeFun(scope.row.dispatchMode)  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="taskStatus" >
        <template #default="scope">
          <span>{{ taskStatusFun(scope.row.taskStatus)  }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="物料状态" align="center" prop="midStatus" /> -->
      <el-table-column label="物料状态" align="center" prop="midStatus" >
        <template #default="scope">
          <span>{{ midStatusFun(scope.row.midStatus)  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="物料编码" align="center" prop="mid" />
      <el-table-column label="物料数量" align="center" prop="num" />
      <!-- <el-table-column label="物资状态" align="center" prop="midType" /> -->
      <el-table-column label="起始位置" align="center" prop="sourceName" width="120"/>
      <el-table-column label="目标位置" align="center" prop="targetName" width="120"/>
      <!-- <el-table-column label="操作员" align="center" prop="operator" /> -->
      
      <el-table-column label="任务创建时间" align="center" prop="rcptim" width="150">
        <template #default="scope">
          <span>{{ parseTime(scope.row.rcptim, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template #default="scope">
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-show="scope.row.taskStatus==0">修改</el-button>
           <el-button link type="primary"  @click="handleExecute(scope.row)" v-show="scope.row.taskStatus==0">执行</el-button>
          <el-button link type="primary"  @click="handleDelete(scope.row)" v-hasPermi="['wisdom:dispatch:remove']" v-show="scope.row.taskStatus==0">删除</el-button>
          
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改调度任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="任务编号" prop="taskNo">
          <el-input v-model="form.taskNo" placeholder="请输入任务编号" />
        </el-form-item>
        <el-form-item label="任务详情" prop="taskDtl">
          <el-input v-model="form.taskDtl" placeholder="请输入任务详情" />
        </el-form-item> -->
        <el-form-item label="物料编码" prop="mid">
          <el-input v-model="form.mid" placeholder="请输入物料编码" />
        </el-form-item>
        <!-- <el-form-item label="物料数量" prop="num">
          <el-input v-model="form.num" placeholder="请输入物料数量" />
        </el-form-item> -->
        <el-form-item label="起始位置" prop="sourceName">
          <el-input v-model="form.sourceName" placeholder="请输入起始位置" />
        </el-form-item>
        <el-form-item label="目标位置" prop="targetName">
          <el-input v-model="form.targetName" placeholder="请输入目标位置" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import { listTask, getTask, delTask, addTask, updateTask,executeTask1,wcsTask,wcsStatus } from "@/api/wisdom/dispatch";

const { proxy } = getCurrentInstance();

const taskList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const wcs_TaskID = ref(-1);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // taskType:1,
    taskNo: null,
    taskDtl: null,
    taskType: null,
    taskStatus: null,
    midStatus: null,
    mid: null,
    midType: null,
    sourceName: null,
    operator: null,
    rcptim: null
  },
  rules: {
    taskNo: [
      { required: true, message: "任务编号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询调度任务列表 */
function getList() {
  loading.value = true;
  // console.log(queryParams.value)
  // if (queryParams.value.taskType == null) {
  //   queryParams.value.taskType = 1;
  // }
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    taskNo: null,
    taskDtl: null,
    taskType: null,
    taskStatus: null,
    midStatus: null,
    mid: null,
    midType: null,
    sourceName: null,
    operator: null,
    rcptim: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加调度任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTask(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改调度任务";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 执行调度任务 */
function handleExecute(row) {
  // console.log(row)
  // return
  proxy.$modal.confirm('是否确认执行调度任务？').then(function() {
    return executeTask(row);
  }).then(() => {
    // getList();
    // proxy.$modal.msgSuccess("执行成功");
  }).catch(() => {});
}
async function executeTask(row) {
  proxy.$modal.msgSuccess("开始执行调度任务");
  if(row.taskType == 0){  //入库
      var first = row.targetName.substr(0,1);
			var aindex = row.targetName.substr(5,1);
      let requestId = ""
      if(first == "A"){
        var Materialstatus = 1;
        if(row.mid == "" || row.mid == "0" || row.mid == 0)
        {
          Materialstatus = 0;
        }
        loading.value = true;
        if(row.dispatchMode == 1){  //仅调立库
            // 向WCS发送入库指令（可能后端自动调用）
            wcsTask({"taskNo":row.taskNo,"materialStatus":Materialstatus,"Location":row.targetName,"mid":row.mid,"num":row.num,dispatchMode:row.dispatchMode}).then(res=>{
              if(res.code==200){
                wcs_TaskID.value = res.taskId;
                proxy.$modal.msgSuccess("WCS入库指令发送成功");
              }else{
                proxy.$modal.msgError("WCS入库指令发送失败!");
                loading.value = false;
              }
            }).catch(() => {
              proxy.$modal.msgError("操作失败");
              loading.value = false;
            });
            var flag3 = false;
						var wcs_finish = false;	
            var timId3 = setInterval(function(){
						// console.log(11111111)
						// console.log(wcs_TaskID.value)
						if(!flag3){
							flag3 = true;
							if(!wcs_finish){
								// wcsStatus({"TaskID": wcs_TaskID.value}).then(res=>{
								// 	flag3 = false;
								// 	if(res.code==200 && res.msg=="200"){
								// 		clearInterval(timId3);   
								// 		wcs_finish = true;
                //     loading.value = false;
                //     proxy.$modal.msgSuccess("立库物资上架完成");
						
								// 	}
								// })
                listTask({taskNo:row.taskNo}).then(response => {
                  flag3 = false;
                  if(response.rows[0].taskStatus == 2){
                    clearInterval(timId3);
                    wcs_finish = true;
                    loading.value = false;
                    proxy.$modal.msgSuccess("立库物资上架完成");
                    getList();
                  }
                });
                
							}
						}
					},60000)
        }else if(row.dispatchMode == 2){  //叉车+立库
            // var agvTargetName = "V01-010101";	//履带的位置叫V01-010101，也是叉车要放货的位置；页面上输入的起始位置V01-230101，指的是叉车取货的开始位置
            // if(aindex == '5' || aindex == '6')
            // {
            //   agvTargetName = "V01-090101";
            // } 
            // // 调用AGV执行接口
            // const agvObj = {"id":row.id,"targetName":agvTargetName,"materialStatus":1}
            // const agvResult = await executeTask(agvObj)
            // //调用AGV成功
            // if(agvResult.code==200){
            //   requestId = agvResult.data.requestId
            //   proxy.$modal.msgSuccess("发送物资移库出入台指令成功");
            //   var flag2 = false;
					  //   var ishow = false;
            //   if(row.targetName == "A01-040903" || row.targetName == "A01-043204"){

            //   }else{
            //       var timId2 = setInterval(function(){
            //         if(flag2) return;
            //         flag2 = true;
            //         //获取AGV执行任务的状态
            //         agvStatus({"requestId": requestId,"status":"TAKE_DOWN_COMPLETED"}).then(res => {
            //           flag2 = false;
            //           if(res.code==200 && res.data !=201){
            //             clearInterval(timId2);
                   
            //             proxy.$modal.msgSuccess("AGV放货至出入台完成");
            //             var Materialstatus = 1;
            //             if(row.mid == "" || row.mid == "0" || row.mid == 0)
            //             {
            //               Materialstatus = 0;
            //             }
            //             // this.taskTips.push("WCS入库指令发送成功")
            //             // 向WCS发送入库指令（可能后端自动调用）
            //             wcsTask({"taskNo":row.taskNo,"materialStatus":Materialstatus,"Location":row.targetName,"mid":row.mid,"num":row.num}).then(res=>{
            //               if(res.code==200){
            //                 wcs_TaskID.value = res.taskId;
            //                 that.taskTips.push("WCS入库指令发送成功")
            //               }else{
            //                 that.taskTips.push("WCS入库指令发送失败!")
            //               }
            //             })
            //           }else{
            //             if(!ishow)
            //             {
            //               that.taskTips.push("等待AGV指令执行完成......")
            //               ishow = true;
            //             }
            //           }
                    
            //         })
            //       },5000)
            //   }
            // }
        }
      }else if(first == "B"){
        //1、给AGV发指令
				//2、检测AGV执行结果
      }
  }else if(row.taskType == 1){  //出库
      var first = row.sourceName.substr(0,1);
      let requestId = ""
      if(first == "A"){
      // console.log(222222)
            var Materialstatus = 1;
            if(row.mid == "" || row.mid == "0" || row.mid == 0)
            {
                Materialstatus = 0;
            }
            loading.value = true;
            // console.log(55555555)
            //调立库（后端调立库、调叉车）
            executeTask1({"id":row.id,"targetName":row.targetName,"materialStatus":Materialstatus,dispatchMode:row.dispatchMode}).then(res=>{
              if(res.code==200){
                // this.wcs_TaskID = res.TaskID;
                if(row.dispatchMode == 1){  // 调立库
                  let flag4 = false;
                  var wcs_finish = false;	
                  let timId4 = setInterval(function(){
                    if(!flag4){
                      flag4 = true;
                      if(!wcs_finish){
                        listTask({taskNo:row.taskNo}).then(response => {
                          flag4 = false;
                          if(response.rows[0].taskStatus == 2){
                            clearInterval(timId4);
                            wcs_finish = true;
                            proxy.$modal.msgSuccess("作业任务完成");
                            loading.value = false;
                            getList();
                          }
                        });
                      }
                    }
                    // 8000
                  },60000)
                }else if(row.dispatchMode == 2){
                  proxy.$modal.msgSuccess("向WCS发送物资出库指令成功");
                  requestId = res.data.requestId
                  proxy.$modal.msgSuccess("发送AGV取货指令成功");
                }
              }else{
                proxy.$modal.msgError("任务执行中,操作失败");
                loading.value = false;
                // this.taskStatus = false;
                return
              }
            }).catch(() => {
              proxy.$modal.msgError("任务执行中,操作失败");
              loading.value = false;
            });
            if(row.dispatchMode == 2){
              // 定时查询 叉车 执行状态
              // 定时查询 叉车 执行状态
              let flag3 = false;
              var agv_finish = false;	
              const that = this
              let timId3 = setInterval(function(){
                if(!flag3){
                  flag3 = true;
                  if(!agv_finish){
                    // END_ARRIVE
                    agvStatus({"requestId": requestId,"status":"TAKE_DOWN_COMPLETED"}).then(res=>{
                      flag3 = false;
                      if(res.code == 200 && res.data != 201){
                        clearInterval(timId3);
                      agv_finish = true;
                      // that.taskTips.push("物资移库完成")
                      // that.taskTips.push("作业任务完成")
                      proxy.$modal.msgSuccess("物资移库完成");
                      proxy.$modal.msgSuccess("作业任务完成");
                      loading.value = false;
                            getList();
                      // that.taskStatus = false;
                      // that.endTask = true
                      // that.$forceUpdate();
                    }
                  })
                }
              }
            },8000)

          }
      }else{
        proxy.$modal.msgSuccess("起始位置有误");
          loading.value = false;
          
      }
  }
  
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除调度任务编号为"' + _ids + '"的数据项？').then(function() {
    return delTask(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wisdom/dispatch/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}
function taskTypeFun(taskType) {
  if (taskType == 0) {
    return '上架'
  } else if (taskType == 1) {
    return '下架'
  } else if(taskType == 2) {
    return '移库'
  }
}
function taskStatusFun(taskStatus) {
  if (taskStatus == 0) {
    return '待执行'
  } else if (taskStatus == 1) {
    return '执行中'
  } else if(taskStatus == 2) {
    return '已完成'
  }else if(taskStatus == -1) {
    return '已取消'
  }
}
function midStatusFun(midStatus) {
  if (midStatus == 0) {
    return '空托'
  } else if (midStatus == 1) {
    return '有货'
  } 
}
function dispatchModeFun(dispatchMode) {
  if (dispatchMode == 1) {
    return '立库'
  } else if (dispatchMode == 2) {
    return '立库+AGV'
  } 
}
getList();
</script>
