<template>
  <div class="layout-pd">
    <!--部件类型-->
    <el-row>
      <!--操作-->
      <el-col :xs="24" >
        <el-card class="mt8" shadow="hover" >
          <el-form :model="state.filterModel" :inline="true" @submit.stop.prevent>
            <el-form-item prop="name" style="width:100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" class="mb20">
                <el-form-item label="物料编号">
                  <el-input v-model="state.filterModel.bomMateNo" placeholder="物料编号" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" class="mb20">
                <el-form-item label="部件名称">
                  <el-input v-model="state.filterModel.bomName" placeholder="部件名称" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" class="mb20">
                <el-form-item label="部件类型">
                  <el-select  v-model="state.filterModel.bomType" placeholder="请选择部件类型" >
                    <el-option v-for="(value, key) in componentType" :key="key" :label="value[1].name"  :value="Number(value[1].value)" />
                  </el-select>
                  </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="4" class="mb20">
                <el-form-item>
                  <el-button type="primary" icon="ele-Search" @click="onQuery"> 查询 </el-button>
                  <el-button type="primary" icon="ele-RefreshRight" @click="onReset"> 重置 </el-button>
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-form>
            <div class="my-flex my-flex-end">
              <el-button  type="primary" icon="ele-CirclePlus" @click="onAdd"> 添加 </el-button>
              <el-button type="primary" icon="ele-UploadFilled" @click="uploadFiles"> 批量导入 </el-button>
              <el-button type="primary" icon="ele-Document" @click="exportTable"> 导出表格 </el-button>
            </div>
        </el-card>
      </el-col>
      <!--表格-->
      <el-col :xs="24" >
        <el-card style="height: 70vh" class="my-fill mt8" shadow="hover">
          <el-table v-loading="state.loading" stripe :data="state.bomListData" row-key="id" style="width: 100%">
            <el-table-column prop="guid" label="序号"  />
            <el-table-column prop="type" label="部件类型"  >
              <template #default="{ row }">
                {{ getComponentType(row.type)}}
              </template>
            </el-table-column>
            <el-table-column prop="bomName" label="部件名称"  />
            <el-table-column prop="bomNo" label="物料号"  />
            <el-table-column prop="status" label="状态"  >
              <template #default="{ row }" >
                <div :style="{color:getComponentState(row.status).color}"  class="bold-font">
                  {{getComponentState(row.status).name}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
            <el-table-column prop="bom_Image" label="部件图片"  >
              <template #default="{ row }">
                <div class="my-flex" @click="showBigPic(row.img)">
                  <el-image
                    :src="getImg(row.img)"
                    :lazy="true"
                    class="img"
                    :hide-on-click-modal="true"
                    fit="contain"
                    preview-teleported
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon><icon-picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
<!--                  <div class="ml10 my-flex-fill my-flex-y-center">-->
<!--                    <div>{{ (row.fileName || '') + (row.extension || '') }}</div>-->
<!--                  </div>-->
                </div>
              </template>
            </el-table-column>

<!--            <el-table-column prop="createdTime" label="更新时间" >-->
<!--              <template #default="{ row }">-->
<!--                {{ formatterTime(row.modifiedTime || row.createdTime || '') }}-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column label="操作"  fixed="right" header-align="center" align="center" class="right-operation" width="100">
              <template #default="{ row }">
                <!-- <el-popover :width="220">
                  <p>{{ row.linkUrl }}</p>
                  <div class="mt10" style="text-align: right; margin: 0">
                    <el-button icon="ele-CopyDocument" size="small" type="primary" @click="copyText(row.linkUrl)">复制地址</el-button>
                  </div>
                  <template #reference>
                    <el-button size="small" text type="primary">地址</el-button>
                  </template>
                </el-popover>
                <el-link
                  class="my-el-link mr12 ml12"
                  :href="row.linkUrl"
                  type="primary"
                  icon="ele-Download"
                  size="small"
                  :underline="false"
                  target="_blank"
                  >下载</el-link
                >
                <el-button v-auth="'api:admin:file:delete'" icon="ele-Delete" size="small" text type="danger" @click="onDelete(row)">删除</el-button> -->
                <el-link
                  class="my-el-link mr12 ml12"
                  @click="editTableData(row)"
                  type="primary"
                  icon="ele-Edit"
                  :underline="false"
                  target="_blank"
                >编辑</el-link>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-flex my-flex-end" style="margin-top: 20px">
            <el-pagination
              v-model:currentPage="state.pageInput.currentPage"
              v-model:page-size="state.pageInput.pageSize"
              :total="state.total"
              :default-page-size="5"
              :page-sizes="[5, 10, 20, 50, 100]"
              small
              background
              @size-change="onSizeChange"
              @current-change="onCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      v-model="state.showBig"
      :close-on-click-modal="true"
      :show-close="false"
      width="80%"
    >
      <img
        :src="getImg(state.imageUrl)"
        class="fullscreen-image"
        alt="放大的图片"/>
    </el-dialog>
    <EditDialog ref="editDialogRef" />
  </div>
</template>

<script lang="ts" setup name="admin/product/bom">
import {defineAsyncComponent, onBeforeMount, onMounted, reactive, ref} from 'vue'
import {ComponentTypeApi} from '/@/api/admin/productionManagement/ComponentType'
import eventBus from '/@/utils/mitt'
import {FileGetPageOutput} from "/@/api/admin/data-contracts";
import {PageInputFileGetPageDto} from "/@/api/admin/productionManagement/ComopnentDto";
import {ComponentGetPageDto} from "/@/api/admin/productionManagement/ComponentTypeDto";
import {Picture as IconPicture} from '@element-plus/icons-vue'
import {useGlobalCacheStore} from "/@/stores/globalCacheStore";



/**引入组件*/
const EditDialog = defineAsyncComponent(() => import('../components/form-edit.vue'))

/**获取全局缓存*/
const globalCacheStore = useGlobalCacheStore()
/**部件类型缓存*/
const componentType = ref(globalCacheStore.getGlobalStore().get('componentType'))
/**获取部件类型列表状态*/
const componentTypeListStatus = ref(globalCacheStore.getGlobalStore()?.get('componentTypeListStatus'))

/**
 * 根据当前环境获取后端的 域名 + 端口
 */
const baseUrl = import.meta.env.VITE_API_URL

/**
 * 绑定EditDialog
 */
const editDialogRef = ref()

// const fileUploadRef = ref()

//部件的页面对象
const state = reactive({
  loading: false,
  fileFormTitle: '',
  showBig: false,
  /**放大图片的url */
  imageUrl: "",
  filterModel: {
    // fileName: '',
    bomType: '',
    bomName: '',
    bomProNo: '',
    bomMateNo: '',
  } as ComponentGetPageDto,
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 5,
  } as PageInputFileGetPageDto,
  bomListData: [] as Array<FileGetPageOutput>,
  bomLogsTitle: '',
})

//const { copyText } = commonFunction()

// const previewImglist = computed(() => {
//   let imgList = [] as string[]
//   state.bomListData.forEach((a) => {
//     if (isImage(a.extension as string) && a.linkUrl) {
//       imgList.push(a.linkUrl as string)
//     }
//   })
//   return imgList
// })

/**查看大图*/
const showBigPic = (val) => {
  // eslint-disable-next-line no-console
  console.log(val)
  state.imageUrl = val
  state.showBig = true
}

/**返回部件类型*/
const getComponentType = (type) =>{
  type = String(type)
  if(componentType.value?.has(type)){
    return componentType.value.get(type).name
  }else {
    return type
  }
}

/**
 * 返回部件类型 - 列表状态
 * @param state
 */
const getComponentState = (state) => {
  state = String(state)
  if(componentTypeListStatus.value.has(state)){
    return componentTypeListStatus.value.get(state)
  }else {
    return state
  }
}

/**
 * 拼接后端的 域名 + 端口
 * @param url
 */
const getImg = (url) => {
  if(url){
    return baseUrl +'/' +url
  }else {
    return ''
  }
}

/**查询*/
const onQuery = async () => {
  state.loading = true
  const {data} = await new ComponentTypeApi().getPage({ ...state.pageInput, filter: state.filterModel }).catch(() => {
    state.loading = false
  })
  state.bomListData = data?.list ?? []
  state.total = data?.total ?? 0
  state.loading = false
}

/**重置*/
const onReset = () => {
  resetSearchForm()
  onQuery()
}

/**重置检索的表单*/
const resetSearchForm = () => {
  state.filterModel.bomType = ''
  state.filterModel.bomName = ''
  state.filterModel.bomProNo = ''
  state.filterModel.bomMateNo = ''
  state.pageInput.currentPage = 1
}

/**
 * 添加操作时直接打开弹窗表单
 * */
const onAdd = () => {
  editDialogRef.value.openDialog()
}

/**
 * 编辑操作时将当前数据对象传递给编辑表单
 * */
const editTableData = (row) => {
  editDialogRef.value.openDialog(row)
}

/**
 * 页条变化
 * @param val
 */
const onSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  onQuery()
}

/**
 * 页数 变化
 * @param val
 */
const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}


/**
 * 挂载时
 */
onMounted(async () => {
  // await initLocalType()
  // await initLocalState()
  await onQuery()
  eventBus.off('refreshView')
  eventBus.on('refreshView', async () => {
    await onQuery()
  })
})

/**
 * 挂载前，
 */
onBeforeMount(() => {
  eventBus.off('refreshView')
})

// const formatterTime = (cellValue: any) => {
//   return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss')
// }

// const getInitialIndex = (imgUrl: string) => {
//   return previewImglist.value.indexOf(imgUrl)
// }

// const onUpload = () => {
//   fileUploadRef.value.open()
// }

//const onDelete = (row: FileGetPageOutput) => {
// proxy.$modal
//.confirmDelete(`确定要删除文件【${row.fileName}${row.extension}】?`)
//.then(async () => {
//  await new BomApi().delete({ id: row.id as number }, { loading: true, showSuccessMessage: true })
// onQuery()
//  })
// .catch(() => {})
// }
</script>

<style scoped lang="scss">
.my-el-link {
  font-size: 14px;
}
.el-form .el-col.mb20 {
  margin: 0 !important;
}
.img {
  width: 100px;
  height: 80px;
  cursor: pointer;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.image-slot .el-icon {
  font-size: 30px;
}
.fullscreen-image {
  width: 100%;
  max-height: 80vh;
  object-fit: contain;
}
.el-input, .el-select {
  width: 240px;
}
.bold-font {
  font-weight: bold;
}
</style>
