<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="下达" prop="orderDate">
        <el-date-picker
          v-model="queryParams.orderDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleQuery"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="交货" prop="deliveryDate">
        <el-date-picker
          v-model="queryParams.deliveryDate"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['mes:task:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:task:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="所有" name="" />
      <el-tab-pane label="草稿" name="0" />
      <el-tab-pane label="送审" name="1" />
      <el-tab-pane label="下达" name="2" />
      <el-tab-pane label="计划" name="3" />
      <el-tab-pane label="开工" name="4" />
      <el-tab-pane label="完工" name="5" />
      <el-tab-pane label="入库" name="6" />
    </el-tabs>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      highlight-current-row
      @current-change="handleCurrentChange"
    >
      <el-table-column label="编码" align="center" prop="code" />
      <el-table-column label="下达日期" align="center" prop="orderDate" :formatter="dateFormatter2" />
      <el-table-column label="交货日期" align="center" prop="deliveryDate" :formatter="dateFormatter2"/>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_TASK_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="操作" align="center" min-width="200px">
        <template #default="scope">
          <el-button link type="info" @click="openItemNeed(scope.row.code, scope.row.id)" v-hasPermi="['mes:task:update']">
            物料
          </el-button>
          <!-- 下达后不可更改-->
          <el-button v-if="scope.row.status<2" link type="success" @click="openSaleForm(scope.row.id)" v-hasPermi="['mes:task:update']">
            销售单
          </el-button>
          <el-button v-if="scope.row.status<2" link type="primary" @click="openForm('update', scope.row.id)" v-hasPermi="['mes:task:update']">
            编辑
          </el-button>
          <el-button v-if="scope.row.status<2" link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:task:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TaskForm ref="formRef" @success="getList" />
  <!-- 表单弹窗：添加/修改 -->
  <TaskAddSaleForm ref="saleFormRef" @success="getList" />
  <!-- 子表的列表 -->
  <ContentWrap>
    <el-tabs model-value="taskDetail">
      <el-tab-pane label="生产任务单明细" name="taskDetail">
        <TaskDetailList :task-id="currentRow.id" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>
  <!-- 物料列表 -->
  <ItemNeedIndex ref="itemFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { TaskApi, TaskVO } from '@/api/mes/task'
import TaskForm from './TaskForm.vue'
import TaskAddSaleForm from './TaskAddSaleForm.vue'
import TaskDetailList from './components/TaskDetailList.vue'
import ItemNeedIndex from "@/views/mes/bom/ItemNeedIndex.vue";

/** 生产任务单 列表 */
defineOptions({ name: 'Task' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TaskVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  orderDate: [],
  deliveryDate: [],
  status: undefined,
  processInstanceId: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskApi.getTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
/** 从销售单添加明细 */
const saleFormRef = ref()
const openSaleForm = (id: number) => {
  saleFormRef.value.open(id)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TaskApi.deleteTask(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TaskApi.exportTask(queryParams)
    download.excel(data, '生产任务单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中行操作 */
const currentRow = ref({}) // 选中行
const handleCurrentChange = (row) => {
  currentRow.value = row
}

/** 初始化 **/
onMounted(() => {
  getList()
})

/** 物料需求 */
const itemFormRef = ref()
const openItemNeed = (taskCode:string, taskId: number) => {
  itemFormRef.value.open("task","任务单-"+taskCode, taskId)
}

/** tab 切换 */
let activeName = ''
const handleTabClick = (tab: TabsPaneContext) => {
  queryParams.status = tab.paneName
  handleQuery()
}
</script>
