<!-- 分包管理样品列表 -->
<script setup lang="ts" name="SelectSample">
import { ref } from 'vue'
import type { Ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { ISampleList } from '../../subpackage-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { OutsourceProjectPassList, detail, listPageBySubpackage } from '@/api/business/subpackage/apply'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { IList } from '@/views/business/subpackage/apply/apply-interface'
import { getSampleListByCertificate } from '@/api/business/subpackage/certificate'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  customerId: {
    type: String,
    default: '',
  },
  orderId: {
    type: String,
    default: '',
  },
  isMulti: {
    type: Boolean,
    default: false,
  },
  customerNo: { // 分包方编号
    type: String,
    default: '',
  },
  outsourcerId: { // 分包方id
    type: String,
    default: '',
  },
})

const emits = defineEmits(['changeVisible', 'clickConfirmSample'])
const sampleType = ref('1') // 默认分包项目
const sampleTypeMap = [
  {
    id: '1',
    name: '分包项目',
  },
  {
    id: '2',
    name: '样品库',
  },
]
// 查询条件
const listQuery = ref({
  sampleName: '',	// 样品名称
  sampleNo: '',	// 样品编号
  offset: 1,
  limit: 20,
})
// 分包项目表头
const columns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center', fixed: true },
  { text: '样品名称', value: 'sampleName', width: '120', align: 'center', fixed: true },
  // { text: '分包方编号', value: 'customerNo', align: 'center' },
  { text: '分包方名称', value: 'customerName', align: 'center' },
  { text: '样品型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center', width: '180px' },
  // { text: '备注', value: 'remark', align: 'center', width: '180px' },
])
// 样品库表头
const sampleColumns = ref<TableColumn[]>([
  { text: '样品编号', value: 'sampleNo', width: '160', align: 'center', fixed: true },
  { text: '样品名称', value: 'sampleName', width: '120', align: 'center', fixed: true },
  { text: '样品型号', value: 'sampleModel', align: 'center' },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center', width: '180px' },
  // { text: '备注', value: 'remark', align: 'center', width: '180px' },
])
// 表格数据
const list = ref<ISampleList[]>([])
// 总数
const total = ref(0)
// 表格加载状态
const loadingTable = ref(false)
// 选中的内容
const checkoutList = ref<string[]>([])

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: any) => {
    return {
      ...item,
      isEdit: false,
    }
  })
}

// ---------------------------------------分包项目----------------------------------------
const projectList = ref<IList[]>([]) // 分包已通过项目列表
const projectListOptions = ref<IList[]>([]) // 申请人列表（用户）--模糊搜索数据
const projectLoading = ref(false) // 申请人模糊搜索框loading
const selectProject = ref('') // 选择的项目
// 获取项目列表
async function fetchProjectList() {
  const params = {
    formId: SCHEDULE.BUSINESS_SUBPACKAGE_APPLY, // 表单id
    outsourcerId: props.outsourcerId || '', // 分包方id
    projectName: '', // 分包项目名称
    projectNo: '', // 分包项目编号
    offset: 1,
    limit: 99999999,
  }
  // 模拟数据
  const response = await OutsourceProjectPassList(params)
  projectList.value = response.data.rows
  projectListOptions.value = response.data.rows
}

// 选择器模糊查询
const remoteMethod = (query: string) => {
  if (query) {
    projectLoading.value = true
    setTimeout(() => {
      projectLoading.value = false
      projectListOptions.value = projectList.value.filter((item) => {
        return item.projectName.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  }
  else {
    projectListOptions.value = projectList.value
  }
}

// 获取详情信息
const getDetail = (id: string) => {
  loadingTable.value = true
  detail({ id, sampleName: listQuery.value.sampleName, sampleNo: listQuery.value.sampleNo }).then((res) => {
    list.value = res.data.sampleList.filter((item: ISampleList) => {
      return item !== null
    })
    list.value = list.value.map((item: ISampleList) => {
      return {
        ...item,
        id: item.sampleId,
      }
    })
    loadingTable.value = false
  })
}

// 选中的项目发生变化
const changeProject = (id: string) => {
  getDetail(id)
}

// --------------------------------------------------------------------------------------

// -----------------------------------------样品库---------------------------------------
// 获取样品库中样品列表
// 数据查询
function fetchData(isNowPage = false) {
  // 查询条件
  const params = {
    customerId: '', // 委托方id
    customerName: '', // 委托方名称
    sampleName: listQuery.value.sampleName, // 样品名称
    sampleNo: listQuery.value.sampleNo, // 样品编号
    offset: listQuery.value.offset,
    limit: listQuery.value.limit,
  }
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getSampleListByCertificate(params).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}

// -----------------------------------------------------------------------------------
// 点击取消
const cancle = () => {
  emits('changeVisible', false)
}

// 点击确定
const clickConfirmSample = () => {
  if (!checkoutList.value.length) {
    ElMessage({
      message: '请选中',
      type: 'warning',
    })
  }
  // 将选择好的样品传给父组件
  emits('clickConfirmSample', checkoutList.value)
  cancle()
}

// 点击搜索
const searchList = () => {
  if (sampleType.value === '1') { // 分包项目
    getDetail(selectProject.value)
  }
  else { // 样品库
    fetchData(true)
  }
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    sampleName: '',	// 样品名称
    sampleNo: '',	// 样品编号
    offset: 1,
    limit: 20,
  }
  if (sampleType.value === '1') { // 分包项目
    getDetail(selectProject.value)
  }
  else { // 样品库
    fetchData(true)
  }
}

watch(() => props.visible, (newValue) => {
  if (newValue) {
    fetchProjectList().then(() => {
      sampleType.value === '1'
      selectProject.value = projectList.value[0].id
      getDetail(projectList.value[0].id) // 默认分包第一个项目
    })
  }
})
watch(sampleType, (newVal) => {
  list.value = []
  if (newVal === '1') { // 分包
    fetchProjectList().then(() => { // 分包项目
      selectProject.value = projectList.value[0].id
      getDetail(projectList.value[0].id)
    })
  }
  else { // 样品库
    fetchData(true)
  }
})
</script>

<template>
  <div class="select-kehu-dialog">
    <el-dialog :modelValue="visible" title="选择样品" width="65%" @close="cancle">
      <search-area
        style="padding-left: 0;padding-right: 0;"
        :need-clear="true"
        @search="searchList" @clear="clearList"
      >
        <search-item>
          <el-input
            v-model.trim="listQuery.sampleNo"
            placeholder="样品编号"
            class="short-input"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.sampleName"
            placeholder="样品名称"
            class="short-input"
            clearable
          />
        </search-item>
        <search-item>
          <el-select v-model="sampleType" class="short-input" placeholder="请选择">
            <el-option
              v-for="item in sampleTypeMap"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </search-item>
        <search-item v-if="sampleType === '1' && projectList.length">
          <!-- <el-input v-model.trim="listQuery.applicantName" placeholder="验收人" class="short-input" clearable /> -->
          <el-select
            v-model="selectProject"
            placeholder="请选择分包项目"
            class="short-input"
            filterable
            remote
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="projectLoading"
            @change="changeProject"
          >
            <el-option v-for="item in projectListOptions" :key="item.id" :label="item.projectName" :value="item.id" />
            <!-- <el-option v-for="item in projectListOptions" :key="item.id" :label="`${item.projectName}(${item.projectNo})`" :value="item.id" /> -->
          </el-select>
        </search-item>
      </search-area>
      <normal-table
        :data="list"
        :total="total"
        :columns="sampleType !== '1' ? sampleColumns : columns"
        :query="listQuery"
        :list-loading="loadingTable"
        :pagination="sampleType !== '1'"
        is-showmulti-select
        :is-multi="isMulti"
        :height="260"
        @change="changePage"
        @multi-select="handleSelectionChange"
      >
        <!-- 序号 -->
        <template #preColumns>
          <el-table-column label="#" width="55" align="center" fixed>
            <template #default="scope">
              {{ (listQuery.offset as number - 1) * (listQuery.limit as number) + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
      </normal-table>
      <template #footer>
        <el-button type="primary" @click="clickConfirmSample">
          确定
        </el-button>
        <el-button @click="cancle">
          取消
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
