<template>
  <div class="layout-pd">
    <!--部件电子档案-->
    <el-row>
      <!--操作-->
      <el-col :xs="24" >
        <el-card class="mt8" shadow="hover" >
          <el-form :model="bomModel.filterModel" :inline="true" @submit.stop.prevent>
            <el-form-item class="form_item" prop="name" style="width:100%">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb20">
                <el-form-item label="物料号">
                  <el-input v-model="bomModel.filterModel.bomMateNo" placeholder="物料号" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb20">
                <el-form-item label="生产编码">
                  <el-input v-model="bomModel.filterModel.bomProNo" placeholder="生产编码" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb20">
                <el-form-item label="部件名称">
                  <el-input v-model="bomModel.filterModel.bomName" placeholder="部件名称" clearable></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" class="mb20">
                <el-form-item label="部件类型">
                  <MySelectRequest :textPla="props.textPla" :select="props.select" :code="props.code" @search="search"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6" 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 v-auth="'api:admin:file:upload-file'" type="primary" icon="ele-Upload" @click="onUpload"> 上传 </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="bomModel.loading" :data="bomModel.bomListData" row-key="id" style="width: 100%">
            <el-table-column prop="guid" label="序号"  />
            <el-table-column prop="bomName" label="部件名称"  />
            <el-table-column prop="bomNo" label="物料号"  />
            <el-table-column prop="bomProNo" label="生产编号"  />
            <el-table-column prop="cpuId" label="CPUID"  />
            <el-table-column prop="software_v" label="软件版本"  />
            <el-table-column prop="status"  label="状态" width="120" >
              <template #default="{ row }">
                <div :style="{color:row.status.color} " class="bold-font">
                  {{row.status.name}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="key_name" label="中化密钥"  >
              <template #default="{ row }">
                <div :style="{color:row.key_name.color}" class="bold-font">
                  {{row.key_name.name}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="stand_name" label="团标状态" >
              <template #default="{ row }">
                <div :style="{color:row.stand_name.color}" class="bold-font">
                  {{row.stand_name.name}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"  />
            <el-table-column prop="remark" label="备注" >
              <!-- <template #default="{ row }">
                <div class="my-flex">
                  <el-image
                    v-if="isImage(row.extension)"
                    :src="row.linkUrl"
                    :preview-src-list="previewImglist"
                    :initial-index="getInitialIndex(row.linkUrl)"
                    :lazy="true"
                    :hide-on-click-modal="true"
                    fit="scale-down"
                    preview-teleported
                    style="width: 80px; height: 80px"
                  />
                  <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">
              <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="toPage(row)"
                  type="primary"
                  icon="ele-Tickets"
                  size="small"
                  :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="bomModel.pageInput.currentPage"
              v-model:page-size="bomModel.pageInput.pageSize"
              :total="bomModel.total"
              :page-sizes="[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>
  </div>
</template>
<script lang="ts" setup name="admin/Component">
import {ref, reactive, onMounted, defineAsyncComponent} from 'vue'  //computed, getCurrentInstance
import { ComponentApi } from '/@/api/admin/productionManagement/Component'
// import dayjs from 'dayjs'
// import eventBus from '/@/utils/mitt'
import {PageInputFileGetPageDto} from "/src/api/admin/productionManagement/ComopnentDto";
import {ComponentGetPageOutPut} from "/src/api/admin/productionManagement/CommunalDto";
import router from "/src/router";
import {sessionStorageSet} from "/src/utils/sessionStorageSet";
import {DictApi} from "/src/api/admin/Dict";
//import { isImage } from '/@/utils/test'
//import commonFunction from '/@/utils/commonFunction'

//const { proxy } = getCurrentInstance() as any
const MySelectRequest = defineAsyncComponent(() => import('/src/components/my-select-request/index.vue'))
/**
 * 向子组件传值，
 * code 字段编码
 * select 默认值
 */
const props = reactive({
  code:'componentType',
  select:'',
  textPla:'请选择部件类型'
})

//设置获取部件中化密钥，团标状态
const componentStatusCode = reactive({
  code:'componentStatus'
})
//部件中化密钥，团标状态对象
const componentStatus = ref()

//设置获取部件状态的编码
const componentStatusTypeCode = reactive({
  code:'componentStatusType'
})
//部件状态对象
const componentStatusType = ref()

const search = (val) => {
  bomModel.filterModel.bomType = val.value
  props.select = val.value
}


const fileUploadRef = ref()

//部件的页面对象
const bomModel = reactive({
  loading: false,
  fileFormTitle: '',
  filterModel: {
    fileName: '',
    bomType: '',
    bomName: '',
    bomProNo: '',
    bomMateNo: '',
  },
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as PageInputFileGetPageDto,
  bomListData: [] as Array<ComponentGetPageOutPut>,
  bomLogsTitle: '',
})


//const { copyText } = commonFunction()

//const previewImglist = computed(() => {
//let imgList = [] as string[]
//bomModel.bomListData.forEach((a) => {

//})
// return imgList
//})

/**
 * 初始化，获取缓存部件状态 中化密钥、团标密钥
 */
const initComponentStatus = async () => {
  let sessionStatus;
  sessionStatus = sessionStorageSet.getItemWithExpiration(componentStatusCode.code as string)
  if (!sessionStatus){
    const res = await new DictApi().getList([componentStatusCode.code] as string[])
    /**存一天的缓存*/
    sessionStorageSet.setItemWithExpiration(componentStatusCode.code as string, res?.data,1)
    sessionStatus = sessionStorageSet.getItemWithExpiration(componentStatusCode.code as string as string)
  }

  /**将状态转化为map的形式*/
  componentStatus.value = sessionStatus.reduce((map, obj) => {
    obj.color = obj.code.split("_")[1]
    map.set(Number(obj.value), {...obj});
    return map;
  },new Map());
}

/**
 * 初始化，获取部件状态缓存
 */
const initComponentStatusType = async () => {
  let sessionStatus;
  sessionStatus = sessionStorageSet.getItemWithExpiration(componentStatusTypeCode.code as string)
  if (!sessionStatus){
    const res = await new DictApi().getList([componentStatusTypeCode.code] as string[])
    /**存一天的缓存*/
    sessionStorageSet.setItemWithExpiration(componentStatusTypeCode.code as string, res?.data,1)
    sessionStatus = sessionStorageSet.getItemWithExpiration(componentStatusTypeCode.code as string as string)
  }

  /**将状态转化为map的形式*/
  componentStatusType.value = sessionStatus.reduce((map, obj) => {
    obj.color = obj.code.split("_")[1]
    map.set(Number(obj.value), {...obj});
    return map;
  },new Map());
}

onMounted(() => {
  /**获取缓存 中化密钥、团标密钥*/
  initComponentStatus()
  /**获取缓存 部件状态*/
  initComponentStatusType()
  onQuery()
})



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

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

const onQuery = async () => {
  bomModel.loading = true
  const res = await new ComponentApi().getPage({ ...bomModel.pageInput, filter: bomModel.filterModel }).catch(() => {
    bomModel.loading = false
  })
  const arr = res?.data?.list
  bomModel.bomListData = arr.map(item => ({
    ...item,
    key_name:componentStatus.value?.get(item.key_name) ?? '',
    stand_name:componentStatus.value?.get(item.stand_name) ?? '',
    status:componentStatusType.value?.get(item.status) ?? ''
  }))
  bomModel.total = res?.data?.total ?? 0
  bomModel.loading = false
}

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

const resetSearchForm = () => {
  bomModel.filterModel.bomType = ''
  bomModel.filterModel.bomName = ''
  bomModel.filterModel.bomProNo = ''
  bomModel.filterModel.bomMateNo = ''
  props.select = ''
}

const onSizeChange = (val: number) => {
  bomModel.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  bomModel.pageInput.currentPage = val
  onQuery()
}

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

const toPage = (row) => {
  router.push({path:`/product/${row.guid}`})
}

//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: 12px;
}
.el-form .el-col.mb20 {
  margin: 0 !important;
}
.el-input {
  width: 240px;
}
.bold-font {
  font-weight: bold;
}
</style>
