<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef"  v-show="showSearch" >
      <el-row :gutter="40">
        <el-col :span="4">
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="queryParams.taskName"
              placeholder="请输入任务名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="任务状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable >
              <el-option v-for="dict in taskStatusDict" :key="dict.id" :label="dict.label" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="仓库" prop="warehouseCode">
            <el-select v-model="queryParams.warehouseCode" placeholder="请选择仓库" clearable >
              <el-option v-for="dict in warehouseData" :key="dict.id" :label="dict.warehouseName" :value="dict.warehouseCode" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="执行人" prop="userId">
            <el-select v-model="queryParams.userId" placeholder="请选择执行人" clearable >
              <el-option v-for="dict in personData" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="盘点类型" prop="taskType">
            <el-select v-model="queryParams.taskType" placeholder="请选择盘点类型" clearable >
              <el-option v-for="dict in taskTypeList" :key="dict.id" :label="dict.label" :value="dict.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <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>

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

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
     
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="场景" align="center" prop="sceneName" />
      <el-table-column label="执行人" align="center" prop="userName" />
      <el-table-column label="要求完成时间" align="center" prop="requireTime" />
      <el-table-column label="任务状态" align="center" >
        <template #default="scope">
          <span>{{ scope.row.status==0?"待执行":(scope.row.status==1?"已完成":"已超时") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="盘点类型" align="center" prop="taskType" >
        <template #default="scope">
          <span>{{ scope.row.taskType==0?"手持盘点":"自动盘点"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务备注" align="center" prop="remark" width="300"/>
      <!-- <el-table-column label="删除状态" align="center" prop="isDelete" >
        <template #default="scope">
          <span>{{ scope.row.isDelete==0?"正常":"已删除"}}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="400">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['Inventory:task:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['Inventory:task:remove']">删除</el-button>
          <el-button link type="primary" :disabled="scope.row.taskType == 0 || (scope.row.taskType == 1 && scope.row.status != 0)" icon="TakeawayBox" @click="handleInventory(scope.row)" v-hasPermi="['Inventory:task:autoInventory']">盘点</el-button>
          <el-button link type="primary" :disabled="scope.row.status != 1" icon="view" @click="handleHistory(scope.row)" v-hasPermi="['Inventory:task:history']">查看结果</el-button>
          <el-button link type="primary" :disabled="scope.row.status != 1" icon="Download" @click="handleExport(scope.row)" v-hasPermi="['Inventory:task:resultExport']">导出</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="800px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseCode">
              <!-- <el-select v-model="form.warehouseId" placeholder="请选择仓库" clearable style="width: 100%">
                <el-option v-for="dict in warehouseData" :key="dict.id" :label="dict.warehouseName" :value="dict.warehouseCode" />
              </el-select> -->
              <el-select v-model="form.warehouseCode" placeholder="请选择仓库" clearable style="width: 100%">
                <el-option v-for="dict in warehouseData" :key="dict.id" :label="dict.warehouseName" :value="dict.warehouseCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场景" prop="sceneId">
              <el-select v-model="form.sceneId" placeholder="请选择场景" clearable style="width: 100%">
                <el-option v-for="dict in sceneData" :key="dict.id" :label="dict.sceneName" :value="dict.sceneCode" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行人" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择执行人" clearable style="width: 100%">
                <el-option v-for="dict in personData" :key="dict.userId" :label="dict.userName" :value="dict.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点类型" prop="taskType">
              <el-select v-model="form.taskType" placeholder="请选择任务类型" clearable style="width: 100%">
                <el-option v-for="dict in taskTypeList" :key="dict.id" :label="dict.label" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="要求完成时间" prop="requireTime">
              <el-date-picker clearable
                style="width:100%"
                v-model="form.requireTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择入库时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="任务备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </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 } from "@/api/Inventory/task";
import {warehouseDict} from "@/api/information/warehouseinfo";
import {listScene} from "@/api/information/scene";
import {personListDict} from "@/api/system/user";    //任务执行人
import { useRouter } from 'vue-router';

const router = useRouter()

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 warehouseData = ref([])   //仓库下拉列表
const sceneData = ref([])   //场景下拉列表
const personData = ref([])    //任务执行人下拉列表
//搜索条件
const taskStatusDict = ref([
  {id:0,label:"待执行"},
  {id:1,label:"已完成"},
  {id:2,label:"已超时"}
])
//搜索条件
const delStatusDict = ref([
  {id:0,label:"正常"},
  {id:1,label:"已删除"}
])
//盘点类型
const taskTypeList = ref([
  {id:"0",label:"手持盘点"},
  {id:"1",label:"自动盘点"}
])
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: null,
    warehouseCode:null,
    status: null,
    userId:null,
    taskType: null
  },
  rules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    warehouseCode: [
      { required: true, message: "仓库不能为空", trigger: "blur" }
    ],
    sceneId: [
      { required: true, message: "场景不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "执行人不能为空", trigger: "blur" }
    ],
    requireTime: [
      { required: true, message: "要求完成时间不能为空", trigger: "blur" }
    ],
    taskType: [
      { required: true, message: "任务类型不能为空", trigger: "change" }
    ],
  }
});

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

/** 查询盘点任务列表 */
function getList() {
  loading.value = true;
  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,
    taskName: null,
    warehouseCode: null,
    sceneId: null,
    userId: null,
    requireTime: null,
    status: null,
    taskType: null,
    remark: null,
    createdBy: null,
    createdAt: null,
    updatedBy: null,
    updatedAt: null,
    isDelete: 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 warehouseList(){
  warehouseDict().then(response=>{
    warehouseData.value = response.data
  })
}
//场景下拉列表
function sceneList(){
  let params = {pageNum:1,pageSize:50}
  listScene(params).then(response=>{
    sceneData.value = response.rows
  })
}
//任务执行人下拉列表
function personList(){
  personListDict().then(response=>{
    personData.value = response.data
  })
}
/** 修改按钮操作 */
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 handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除？').then(function() {
    return delTask(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 盘点操作 */
function handleInventory(row) {
  router.push({ path: "/Inventory/task/autoInventory" , query: {"taskId": row.id} })
}

/** 查看结果操作 */
function handleHistory(row) { 
  router.push({ path: "/Inventory/task/inventoryResult" , query: {"taskId": row.id,'warehouseCode':row.warehouseCode,"sceneId":row.sceneId} })
}

/** 导出按钮操作 */
function handleExport(row) {
  // let taskId = row.id
  let obj = {
    sceneId: row.sceneId,
    warehouseCode: row.warehouseCode,
  }
  proxy.download('/MatchScan/exportInventory', obj, `${row.taskName}_${new Date().getTime()}.xlsx`)
}

getList();
warehouseList();  //库房
  sceneList();    //场景
  personList()  //任务执行人
</script>
