<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px task-search-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      min-label-width="68px"
    >
      <el-form-item :label="t('ProductionPlan.Task.searchCodeLabel')" prop="code">
        <el-input
          v-model="queryParams.code"
          :placeholder="t('ProductionPlan.Task.searchCodePlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Task.searchOrderLabel')" prop="orderDate">
        <el-date-picker
          v-model="queryParams.orderDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleQuery"
          type="daterange"
          :start-placeholder="t('ProductionPlan.Task.searchOrderStartPlaceholder')"
          :end-placeholder="t('ProductionPlan.Task.searchOrderEndPlaceholder')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-280px"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Task.searchDeliveryLabel')" prop="deliveryDate">
        <el-date-picker
          v-model="queryParams.deliveryDate"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('ProductionPlan.Task.searchDeliveryStartPlaceholder')"
          :end-placeholder="t('ProductionPlan.Task.searchDeliveryEndPlaceholder')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-280px"
        />
      </el-form-item>

      <el-form-item :label="t('ProductionPlan.Task.searchRemarkLabel')" prop="remark" v-show="showAllFilters">
        <el-input
          v-model="queryParams.remark"
          :placeholder="t('ProductionPlan.Task.searchRemarkPlaceholder')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.Task.searchCreateTimeLabel')" prop="createTime" v-show="showAllFilters">
        <el-date-picker
          v-model="queryParams.createTime"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          :start-placeholder="t('ProductionPlan.Task.searchCreateTimeStartPlaceholder')"
          :end-placeholder="t('ProductionPlan.Task.searchCreateTimeEndPlaceholder')"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-280px"
        />
      </el-form-item>
    
      <el-form-item v-if="filterCount > 3">
        <el-button plain @click="toggleFilters">
          <Icon :icon="showAllFilters ? 'ep:arrow-up' : 'ep:arrow-down'" class="mr-5px" />
          {{ showAllFilters ? '收起' : '更多' }}
        </el-button>
      </el-form-item>
    
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('ProductionPlan.Task.buttonSearchText') }}</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('ProductionPlan.Task.buttonResetText') }}</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['mes:task:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> {{ t('ProductionPlan.Task.buttonCreateText') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['mes:task:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> {{ t('ProductionPlan.Task.buttonExportText') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane :label="t('ProductionPlan.Task.tabAllLabel')" name="" />
      <el-tab-pane :label="t('ProductionPlan.Task.tabDraftLabel')" name="0" />
      <el-tab-pane :label="t('ProductionPlan.Task.tabSubmitLabel')" name="1" />
      <el-tab-pane :label="t('ProductionPlan.Task.tabIssuedLabel')" name="2" />
    <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabPartialSchedulingLabel')" name="7" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabPendingProductionLabel')" name="8" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabInProductionLabel')" name="9" />
      <el-tab-pane :label="t('ProductionPlan.TaskSummary.tabCompletedLabel')" name="10" />
    </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="t('ProductionPlan.Task.tableCodeColumn')" align="center" prop="code"  sortable/>
      <el-table-column :label="t('ProductionPlan.Task.tableOrderDateColumn')" align="center" prop="orderDate" :formatter="dateFormatter2" sortable/>
      <el-table-column :label="t('ProductionPlan.Task.tableDeliveryDateColumn')" align="center" prop="deliveryDate" :formatter="dateFormatter2" sortable/>
      <el-table-column :label="t('ProductionPlan.Task.tableTaskTypeColumn')" align="center" prop="taskType" sortable>
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_TASK_TYPE" :value="scope.row.taskType" />
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.tableIsUrgentColumn')" align="center" prop="isUrgent" sortable>
        <template #default="scope">
          <el-tag :type="String(scope.row.isUrgent) === '1' ? 'danger' : 'info'">
            {{ String(scope.row.isUrgent) === '1' ? t('ProductionPlan.Task.urgentYesLabel') : t('ProductionPlan.Task.urgentNoLabel') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.tableStatusColumn')" align="center" prop="status" sortable>
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MES_TASK_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column :label="t('ProductionPlan.Task.tableRemarkColumn')" align="center" prop="remark" />

      <el-table-column :label="t('ProductionPlan.Task.tableOperateColumn')" align="center" min-width="200px">
        <template #default="scope">
          <el-button v-if="scope.row.status==0" link type="primary" @click="changeStatus(t('ProductionPlan.Task.actionSubmitLabel'),1, scope.row.id)" v-hasPermi="['mes:task:update']">
            {{ t('ProductionPlan.Task.actionSubmitLabel') }}
          </el-button>
          <el-button v-if="scope.row.status==1" link type="primary" @click="changeStatus(t('ProductionPlan.Task.actionApproveLabel'),2, scope.row.id)" v-hasPermi="['mes:task:approve']">
            {{ t('ProductionPlan.Task.actionApproveLabel') }}
          </el-button>
          <el-button link type="info" @click="openItemNeed(scope.row.code, scope.row.id)" v-hasPermi="['mes:task:update']">
            {{ t('ProductionPlan.Task.actionMaterialLabel') }}
          </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']">
            {{ t('ProductionPlan.Task.actionEditLabel') }}
          </el-button>
          <el-button v-if="scope.row.status<2" link type="danger" @click="handleDelete(scope.row.id)" v-hasPermi="['mes:task:delete']">
            {{ t('ProductionPlan.Task.actionDeleteLabel') }}
          </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 v-if="currentRow?.id" model-value="taskDetail" v-model="activeListName" @tab-click="handleListTabClick">
      <el-tab-pane :label="t('ProductionPlan.Task.detailTabTaskDetailLabel')" name="taskDetail">
        <template v-if="activeListName === 'taskDetail'">
          <TaskDetailList
            :task-id="currentRow.id"
            :task-status="currentRow.status"
            :show-create-button="['0', '1'].includes(String(currentRow.status))"
          />
        </template>
      </el-tab-pane>
<!--      <el-tab-pane label="任务单明细进度" name="taskDetailProgress">-->
<!--        <TaskDetailList v-if="activeListName ==='taskDetailProgress'" :task-id="currentRow.id" />-->
<!--      </el-tab-pane>-->
    </el-tabs>
    <el-empty v-else :description="t('ProductionPlan.Task.selectTaskTip')" />
  </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: [],
  taskType: undefined,
  status: undefined,
  processInstanceId: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const showAllFilters = ref(false) // 是否显示所有筛选框
const filterCount = 4 // 筛选框数量

/** 切换筛选框展开/折叠 */
const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
}

/** 查询列表 */
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
  currentRow.value = {}
  console.log(currentRow.value)
  handleQuery()
}
/** 送审/审核 */
const changeStatus = async (type:string, status: number, id: number) => {
  try {
    // 删除的二次确认
    await message.confirm("确认"+type+"?")
    // 发起删除
    await TaskApi.changeStatus(status, id)
    message.success(type+"成功！")
    // 刷新列表
    await getList()
  } catch {}
}

/** tab 切换 */
let activeListName = 'taskDetail'

</script>

<style scoped>
.task-search-form {
  display: flex;
  flex-wrap: wrap;
}
.task-search-form :deep(.el-form-item) {
  margin-right: 16px;
}
</style>
