<template>
  <div class="goodInfo layout-pd" >
    <!--部件详情-->
    <el-row>
      <!-- 基础信息 -->
      <el-col :xs="24" >
        <el-card shadow="hover" header="基础信息">
          <div class="basicInformation" v-loading="goods.loadingBasic">
            <div class="basicInformation-left">
              <div class="item ">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="物料名称"
                  trigger="hover"
                  :content="goods.basicInformation.bomName"
                >
                  <template #reference>
                    <span class="m-2"> 物料名称: {{goods.basicInformation.bomName}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="物料号"
                  trigger="hover"
                  :content="goods.basicInformation.bomNo"
                >
                  <template #reference>
                    <span class="m-2"> 物料号: {{goods.basicInformation.bomNo}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="CPUID"
                  trigger="hover"
                  :content="goods.basicInformation.cpuId"
                >
                  <template #reference>
                    <span class="m-2"> CPUID: {{goods.basicInformation.cpuId}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="软件版本"
                  trigger="hover"
                  :content="goods.basicInformation.software_v"
                >
                  <template #reference>
                    <span class="m-2"> 软件版本: {{goods.basicInformation.software_v}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="状态"
                  trigger="hover"
                  :content="goods.basicInformation.status"
                >
                  <template #reference>
                    <span class="m-2 ">
                      状态:
                      <span class="bold-font" :style="{color:goods.basicInformation.status?.color}">
                        {{goods.basicInformation.status?.name ?? ''}}
                      </span>
                    </span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="中化密钥"
                  trigger="hover"
                  :content="goods.basicInformation.key_name"
                >
                  <template #reference>
                    <span class="m-2">
                      密钥状态:
                      <span class="bold-font" :style="{color:goods.basicInformation.key_name?.color}">
                        {{goods.basicInformation.key_name?.name ?? ''}}
                      </span>
                    </span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="团标状态"
                  trigger="hover"
                  :content="goods.basicInformation.stand_name"
                >
                  <template #reference>
                    <span class="m-2 ">
                      团标状态:
                      <span class="bold-font" :style="{color:goods.basicInformation.stand_name?.color}">
                        {{goods.basicInformation.stand_name?.name ?? ''}}
                      </span>
                    </span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="创建时间"
                  trigger="hover"
                  :content="goods.basicInformation.createTime"
                >
                  <template #reference>
                    <span class="m-2"> 创建时间: {{goods.basicInformation.createTime}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  trigger="hover"
                  title="备注"
                  :content="goods.basicInformation.remark"
                >
                  <template #reference>
                    <span class="m-2"> 备注: {{goods.basicInformation.remark}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="检测时间"
                  trigger="hover"
                  :content="goods.basicInformation.detectionTime"
                >
                  <template #reference>
                    <span class="m-2"> 检测时间: {{goods.basicInformation.detectionTime}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
                <el-popover
                  placement="top-start"
                  :width="200"
                  title="检测员"
                  trigger="hover"
                  :content="goods.basicInformation.detectionEmployee"
                >
                  <template #reference>
                    <span class="m-2"> 检测员: {{goods.basicInformation.detectionEmployee}}</span>
                  </template>
                </el-popover>
              </div>
              <div class="item">
              </div>
            </div>
            <div class="basicInformation-right" >
                <div @click="showBigPic(goods.basicInformation.img)">
                  <el-image loading="lazy"
                            alt="fgg"
                            class="img"
                            fit="contain"
                            :src="baseUrl + '/' + goods.basicInformation.img" >
                    <template #error>
                      <div class="image-slot">
                        <el-icon><icon-picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </div>
              </div>
          </div>
        </el-card>
      </el-col>

      <!-- 生产日志 -->
      <el-col :xs="24" >
        <el-card style="height: 40vh" class="my-fill mt8"  shadow="hover" header="生产日志">
          <el-table v-loading="goods.loadingProduct" :data="goods.productionLog.tableData" row-key="id" style="width: 100%">
            <el-table-column prop="alarmDate" label="生产时间"  />
            <el-table-column prop="eventName" label="操作员"  />
            <el-table-column prop="step" label="工序"  >
              <template #default="{ row }">
                {{row.step}}
              </template>
            </el-table-column>
            <el-table-column prop="state" label="状态"  >
              <template #default="{ row }">
                {{row.state ? "正常" : "异常"}}
              </template>
            </el-table-column>
            <el-table-column prop="img" label="生产图片"  >
              <template #default="{ row }">
                <el-link :underline="false" @click="showBigPic(row.img)">查看大图</el-link>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注"  />
<!--            <el-table-column v-for="column in goods.productionLog.dynamicColumns" :key="column.prop" :prop="column.prop" :label="column.label"  />-->
          </el-table>
          <div class="my-flex my-flex-end"  style="margin-top: 20px">
            <el-pagination
              v-model:currentPage="goods.productionLog.pageInput.CurrentPage"
              v-model:page-size="goods.productionLog.pageInput.PageSize"
              :default-page-size="5"
              :total="goods.productionLog.total"
              :page-sizes="[5, 10, 20, 50, 100]"
              small
              background
              @size-change="onProductionLogSizeChange"
              @current-change="onProductionLogCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 报警日志 -->
      <el-col :span="24" >
        <el-card style="height: 40vh" class="my-fill mt8" shadow="hover" header="报警日志">
          <el-table v-loading="goods.loadingAlarm" :data="goods.alarmLog.tableData" row-key="id" style="width: 100%">
            <el-table-column v-for="column in goods.alarmLog.dynamicColumns" :key="column.prop" :prop="column.prop" :label="column.label"  />
          </el-table>
          <div class="my-flex my-flex-end"  style="margin-top: 20px">
            <el-pagination
              v-model:currentPage="goods.alarmLog.pageInput.CurrentPage"
              v-model:page-size="goods.alarmLog.pageInput.PageSize"
              :total="goods.alarmLog.total"
              :page-sizes="[5, 10, 20, 50, 100]"
              :default-page-size="5"
              small
              background
              @size-change="onAlarmLogSizeChange"
              @current-change="onAlarmLogCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!--大图显示-->
    <el-dialog
      v-model="goods.showBig"
      :close-on-click-modal="true"
      :show-close="false"
      width="80%"
    >
      <img
        :src="goods.imageUrl"
        class="fullscreen-image"
        alt="放大的图片"/>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="goodInfo">
import {onMounted, reactive, ref} from "vue";
import {ComponentDetails} from "/@/api/admin/productionManagement/ComponentDetails";
import router from "/@/router";
import type {
  alarmLog,
  goodsInformationBasic,
  productionLog
} from "/@/api/admin/productionManagement/ComponentDetailsDto";
import {adminProductGoodsInfoDto, filterData} from "/@/api/admin/productionManagement/ComponentDetailsDto";
import type {columnsProps, pageInput} from "/@/api/admin/shareDto/shareDto";
import { Picture as IconPicture } from '@element-plus/icons-vue'
import {sessionStorageSet} from "/@/utils/sessionStorageSet";
import {DictApi} from "/@/api/admin/Dict";
import {ProductionLogRequestBody} from "/@/api/admin/productionManagement/ComopnentDto";
//组件的页面对象
const goods = reactive({
  /**部件id */
  id:"",
  /**页面请求参数*/
  data:{} as filterData,
  /**显示加载效果 */
  loadingBasic: false,
  loadingProduct: false,
  loadingAlarm: false,
  /**图片是否方法显示 */
  showBig: false,
  /**放大图片的url */
  imageUrl: "",
  /**基础信息 */
  basicInformation: {} as goodsInformationBasic,

  /**生产日志 */
  productionLog: {
    /**表格数据 */
    tableData:  [] as Array<productionLog>,
    /**动态表头 */
    // dynamicColumns: [
    //   { prop: 'alarmDate', label: '生产时间' },
    //   { prop: 'eventName', label: '操作员  ' },
    //   { prop: 'step', label: '工序' },
    //   { prop: 'state', label: '状态' },
    //   { prop: 'img', label: '生产图片' },
    //   { prop: 'remarks', label: '备注' },
    // ] ,
    /**页面分页 */
    pageInput: {
      CurrentPage: 1,
      PageSize: 5
    } as pageInput,
    /**总数 */
    total: 0
  } as productionLog,
  /**报警日志 */
  alarmLog: {
    /**表格数据 */
    tableData:  [] as Array<alarmLog>,
    /**动态表头 */
    dynamicColumns: [] as Array<columnsProps>,
    /**页面分页 */
    pageInput: {
      CurrentPage: 1,
      PageSize: 5
    } as pageInput,
    /**总数 */
    total: 0
  } as alarmLog,
} as adminProductGoodsInfoDto)

//图片url前缀
const baseUrl = import.meta.env.VITE_API_URL

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

/**生产日志分页size变化 */
const onProductionLogSizeChange = (val) => {
  goods.productionLog.pageInput.PageSize = val
  initProductionLog()
}

/**生产日志分页Current变化 */
const onProductionLogCurrentChange = (val) => {
  goods.productionLog.pageInput.CurrentPage = val
  initProductionLog()
}

/**报警日志分页size变化 */
const onAlarmLogSizeChange = (val) => {
  goods.alarmLog.pageInput.CurrentPage = val
  initAlarmLog()
}

/**报警日志分页Current变化 */
const onAlarmLogCurrentChange = (val) => {
  goods.alarmLog.pageInput.CurrentPage = val
  initAlarmLog()
}


/**
 * 初始化数据
 */
const initBasicInformation =  async () => {
  goods.loadingBasic = true
  const { data } = await new ComponentDetails().getBasicInfo({GUID:goods.id} ).catch(() => {
    goods.loadingBasic = false
  })
  goods.basicInformation = ({
    ...data,
    status: componentStatusType.value?.get(data.status) ?? '',
    key_name:basicInformationStatus.value?.get(data.key_name) ?? '',
    stand_name:basicInformationStatus.value?.get(data.stand_name) ?? ''
  })
  goods.loadingBasic = false
}

const initProductionLog = async () => {
  goods.loadingProduct = true
  const { data } = await new ComponentDetails().getProductionLog({...goods.productionLog.pageInput,filter:({id:goods.id})} as ProductionLogRequestBody)
  goods.productionLog.tableData = data?.list?.reduce((arr, item) => {
    item.step = productionLogStatus.value?.get(item.step).name
    arr.push(item)
    return arr
  },[]) ?? []
  goods.productionLog.total = data?.total ?? 0
  goods.loadingProduct = false
}

const initAlarmLog = async () => {
  goods.loadingAlarm = true
  goods.alarmLog = await new ComponentDetails().getAlarmLog(goods.productionLog.pageInput, goods.id)
  goods.loadingAlarm = false
  // console.log(goods.alarmLog)
}

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

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

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

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

  /**将状态转化为map的形式*/
  basicInformationStatus.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());
}

/**
 * 初始化，获取生产日志工序缓存
 */
const initProductionLogCache = async () => {
  let sessionStatus;
  sessionStatus = sessionStorageSet.getItemWithExpiration(productionLogStatusCode.code as string)
  if (!sessionStatus){
    const res = await new DictApi().getList([productionLogStatusCode.code] as string[])
    /**存一天的缓存*/
    sessionStorageSet.setItemWithExpiration(productionLogStatusCode.code as string, res?.data,1)
    sessionStatus = sessionStorageSet.getItemWithExpiration(productionLogStatusCode.code as string as string)
  }

  /**将状态转化为map的形式*/
  productionLogStatus.value = sessionStatus.reduce((map, obj) => {
    map.set(Number(obj.value), {...obj});
    return map;
  },new Map());
}


onMounted(() => {
  goods.id = router.currentRoute.value.params.guid
  // console.log(goods.productionLog.pageInput.PageSize)
  initBasicInformationCache()
  initComponentStatusType()
  initProductionLogCache()
  /**初始化 */
  initBasicInformation()
  initProductionLog()
  initAlarmLog()
})

</script>
<style scoped lang="scss">
.goodInfo{
  font-weight: 500;
  .el-card{
    margin-bottom: 20px;
  }


  .basicInformation{
    display: flex;
    display: -webkit-flex; /* Safari */
    justify-content: space-around;
    align-items:center;
    align-content:space-around;
    flex-wrap: wrap-reverse;
    .basicInformation-left{
      display: flex;
      display: -webkit-flex; /* Safari */
      justify-content: space-around;
      flex-wrap: wrap;
      height: 100%;
      max-width: 65%;
      min-width: 300px;
      .item{
        cursor: pointer;
        width: 240px;/*设置显示的最大宽度*/
        height:40px;
        overflow:hidden;/*超出部分隐藏*/
        white-space:nowrap;/*强制单行显示*/
        text-overflow: ellipsis;
        display: flex;
        align-items: center;

        .bold-font{
          font-weight: bold;
        }
      }

    }
    .basicInformation-right{
      width: 50%;
      height: 100%;
      max-width: 300px;
      min-width: 200px;
      padding: 0 10px;
      .img {
        width: 220px;
        height: 140px;
        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;
  }
}
</style>
