<template>
  <ContentWrap>
    <Search
      :schema="schema"
      :model="queryParams"
      :expand="true"
      :expandDefault="false"
      expand-field="supplierName"
      :inline="true"
      @search="handleQuery"
      @reset="resetQuery"
    >
      <template #actionMore>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['contract:quality-notice:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          v-hasPermi="['contract:quality-notice:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          @click="handleDeleteBatch"
          v-hasPermi="['contract:quality-notice:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </template>
    </Search>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <!-- 基础信息 -->
      <el-table-column label="送检单号" align="center" prop="inspectionNo" width="150" />
      <el-table-column label="批次号" align="center" prop="batchNo" width="120" />
      <el-table-column label="物料编码" align="center" prop="materialCode" width="120" />

      <!-- 数量信息 -->
      <el-table-column label="检验批数量" align="center" prop="inspectionQuantity" width="120" />
      <el-table-column label="不合格数量" align="center" prop="unqualifiedQuantity" width="120" />

      <!-- 质量问题 -->
      <el-table-column
        label="不合格原因"
        align="center"
        prop="unqualifiedReason"
        width="180"
        show-overflow-tooltip
      />
      <el-table-column
        label="不合格描述"
        align="center"
        prop="unqualifiedDescription"
        width="200"
        show-overflow-tooltip
      />

      <!-- 供应商信息 -->
      <el-table-column
        label="供应商名称"
        align="center"
        prop="supplierName"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column label="采购订单号" align="center" prop="purchaseOrderNo" width="150" />

      <!-- 处理信息 -->
      <el-table-column label="问题来源类型" align="center" prop="problemSourceType" width="140">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CONTRACT_QUALITY_ISSUE_SOURCE_TYPE" :value="scope.row.problemSourceType" />
        </template>
      </el-table-column>
      <el-table-column
        label="限制处理时间"
        align="center"
        prop="limitProcessingTime"
        width="160"
        :formatter="dateFormatter2"
      />

      <!-- 异议信息 -->
      <el-table-column label="供方异议" align="center" width="140">
        <template #default="{ row }">
          <span>{{ row.isSupplierObjectionAccepted == '1' ? '接收' : '未接收' }}</span>
          <span v-if="row.supplierObjectionRemark">(有备注)</span>
        </template>
      </el-table-column>

      <!-- 其他信息 -->
      <el-table-column
        label="物料使用部门"
        align="center"
        prop="materialUseDepartment"
        width="140"
      />
      <el-table-column label="附件" align="center" prop="attachmentInfo" width="100" />

      <!-- 时间信息 -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="160"
        :formatter="dateFormatter"
      />

      <!-- 操作列 -->
      <el-table-column label="操作" align="center" fixed="right" width="120">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['contract:quality-notice:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['contract:quality-notice: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>

  <!-- 表单弹窗：添加/修改 -->
  <QualityNoticeForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { QualityNoticeApi, QualityNoticeVO } from '@/api/contract/qualitynotice'
import QualityNoticeForm from './QualityNoticeForm.vue'
import { Search } from '@/components/Search'
import { FormSchema } from '@/types/form'

/** 质量通知单 列表 */
defineOptions({ name: 'ContractQualityNotice' })
const issueSourceTypeOptions = getIntDictOptions(DICT_TYPE.CONTRACT_QUALITY_ISSUE_SOURCE_TYPE)
// 搜索表单配置
const schema: FormSchema[] = [
  // 第一行：主要编号信息
  {
    field: 'inspectionNo',
    label: '送检单号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入送检单号',
      clearable: true,
      class: '!w-200px'
    }
  },
  {
    field: 'batchNo',
    label: '批次号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入批次号',
      clearable: true,
      class: '!w-200px'
    }
  },
  {
    field: 'materialCode',
    label: '物料编码',
    component: 'Input',
    componentProps: {
      placeholder: '请输入物料编码',
      clearable: true,
      class: '!w-200px'
    }
  },
  {
    field: 'purchaseOrderNo',
    label: '采购订单号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入采购订单号',
      clearable: true,
      class: '!w-200px'
    }
  },

  // 第二行：供应商相关信息
  {
    field: 'supplierName',
    label: '供应商名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入供应商名称',
      clearable: true,
      class: '!w-200px'
    }
  },
  {
    field: 'supplierCode',
    label: '供应商编码',
    component: 'Input',
    componentProps: {
      placeholder: '请输入供应商编码',
      clearable: true,
      class: '!w-200px'
    }
  },
  {
    field: 'materialUseDepartment',
    label: '物料使用部门',
    component: 'Input',
    componentProps: {
      placeholder: '请输入物料使用部门',
      clearable: true,
      class: '!w-200px'
    }
  },

  // 第三行：数量相关信息
  {
    field: 'inspectionQuantity',
    label: '检验批数量',
    component: 'Input',
    componentProps: {
      placeholder: '请输入检验批数量',
      clearable: true,
      class: '!w-200px'
    }
  },
  {
    field: 'unqualifiedQuantity',
    label: '不合格数量',
    component: 'Input',
    componentProps: {
      placeholder: '请输入不合格数量',
      clearable: true,
      class: '!w-200px'
    }
  },
  {
    field: 'problemSourceType',
    label: '问题来源类型',
    component: 'Select',
    componentProps: {
      placeholder: '请选择',
      clearable: true,
      options: issueSourceTypeOptions,
      class: '!w-200px'
    }
  },

  // 第四行：时间相关信息
  {
    field: 'limitProcessingTime',
    label: '限制处理时间',
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')],
      class: '!w-240px'
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    component: 'DatePicker',
    componentProps: {
      type: 'daterange',
      startPlaceholder: '开始日期',
      endPlaceholder: '结束日期',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')],
      class: '!w-240px'
    }
  }
]
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const currentRow = ref()
const loading = ref(true) // 列表的加载中
const list = ref<QualityNoticeVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  inspectionNo: '',
  batchNo: '',
  materialCode: '',
  purchaseOrderNo: '',
  supplierName: '',
  supplierCode: '',
  materialUseDepartment: '',
  inspectionQuantity: '',
  unqualifiedQuantity: '',
  problemSourceType: '',
  limitProcessingTime: [],
  createTime: []
})
const exportLoading = ref(false) // 导出的加载中

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

/** 搜索按钮操作 */
const handleQuery = (model) => {
  // 必须手动更新 queryParams！
  queryParams.value = { ...queryParams.value, ...model } // 合并数据
  getList()
}

/** 重置按钮操作 */
const resetQuery = (model) => {
  queryParams.value = { ...queryParams.value, ...model } // 合并数据
  getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await QualityNoticeApi.deleteQualityNotice(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除质量通知单 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await QualityNoticeApi.deleteQualityNoticeList(checkedIds.value)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: QualityNoticeVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await QualityNoticeApi.exportQualityNotice(queryParams.value)
    download.excel(data, '质量通知单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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