<template>
  <ContentWrap>
    <el-tabs v-model="activeTab" type="border-card" tab-position="left" v-loading="loading" style="height: 84vh">
      <el-tab-pane
        style="height: 100%"
        v-for="(item,index) in list"
        :key="index"
      >
        <template #label>
<!--          <span  @click="openFill(item.deviceCategoryId,item.deviceId,item.deptId,item.deviceName,item.deviceCode)">
           {{item.deviceCode}} ({{ item.deviceName }})
          </span>-->
          <span class="custom-label" v-if='item.isFill === 1' @click="openFill(item.deviceCategoryId,item.deviceId,item.deptId,item.deviceName,item.deviceCode)">
           {{item.deviceCode}} ({{ item.deviceName }})
          </span>
          <span v-else  @click="openFill(item.deviceCategoryId,item.deviceId,item.deptId,item.deviceName,item.deviceCode)">
           {{item.deviceCode}} ({{ item.deviceName }})
          </span>
        </template>
        <div class="form-wrapper">
          <el-form label-width="120px">
            <div style="margin-left: 24px">
              <el-form class="demo-form-inline" :inline="true">
                <el-form-item label="所属队伍:">
                  {{item.orgName}}
                </el-form-item>
                <el-form-item label="累计运行时间:">
                  {{totalRunTime1}}h
                </el-form-item>
              </el-form>
            </div>
            <div v-for="(item,index) in attrList" :key="index">
                <el-form-item :label='item.name' prop="deviceId" v-if="item.name==='当日运转时间'" >
                  <el-input
                    v-model="item.fillContent" @input="attrList[index].fillContent = $event.target.fillContent"
                    clearable
                    style="width: 200px"
                    disabled
                  />
                </el-form-item>
              <el-form-item :label='item.name' prop="deviceId" v-else>
                <el-input
                  v-model="item.fillContent" @input="attrList[index].fillContent = $event.target.fillContent"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="info" @click="deleteFillInfo">取消</el-button>
              <el-button type="primary" @click="getFillInfo">确定</el-button>
            </el-form-item>
          </el-form>
        </div>



      </el-tab-pane>
    </el-tabs>
  </ContentWrap>

</template>

<script setup lang="ts">
import { dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { IotOpeationFillApi, IotOpeationFillVO } from '@/api/pms/iotopeationfill'
import IotOpeationFillForm from './IotOpeationFillForm.vue'
import Vue from "@vitejs/plugin-vue";
import {useUserStore} from "@/store/modules/user";


/** 运行记录填报 列表 */
defineOptions({ name: 'IotOpeationFill' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const loading = ref(true) // 列表的加载中
const { params, name } = useRoute() // 查询参数
const deptId = params.id
const list = ref<IotOpeationFillVO[]>([]) // 列表的数据
const attrList = ref<IotOpeationFillVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const arry1 =ref([]);
let totalRunTime1: string = '123'
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceCode: undefined,
  deviceName: undefined,
  fillContent: undefined,
  deviceType: undefined,
  deviceComponent: undefined,
  deptId: undefined,
  orgName: undefined,
  proId: undefined,
  proName: undefined,
  teamId: undefined,
  teamName: undefined,
  dutyName: undefined,
  creDate: [],
  createTime: [],
  deviceCategoryId:1,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


const formatDescription = async(row, column, cellValue) =>{
  return cellValue.split(',').map(part => `<div>${part}</div>`).join('');
}


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.deptId = deptId.split(",")[0];
    queryParams.userId = deptId.split(",")[1];
    queryParams.createTime = formatTimestamp(JSON.parse(deptId.split(",")[2]));
    const data = await IotOpeationFillApi.getIotOpeationFillPage(queryParams)
    list.value = data;
    list.value.forEach(function (item, index) {
      arry1.value[index] = item;
    });
    queryParams.deviceCategoryId = arry1.value[0].deviceCategoryId
    queryParams.deptId = arry1.value[0].deptId;
    queryParams.deviceCode = arry1.value[0].deviceCode;
    queryParams.deviceName = arry1.value[0].deviceName;
    queryParams.deviceId = arry1.value[0].deviceId;
    getAttrList();
  } finally {
    loading.value = false
  }
}
function formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}
const open = async (type: string, id?: number) => {
  alert(id)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const openFill = (deviceCategoryId?:number,deviceId?:number,deptId?:number,deviceName?:string,deviceCode?:string) =>{
  queryParams.deviceCategoryId = deviceCategoryId;
  queryParams.deptId = deptId;
  queryParams.deviceCode = deviceCode;
  queryParams.deviceName = deviceName;
  queryParams.deviceId = deviceId;
  getAttrList();
}


const getAttrList = async () => {
  loading.value = true
  try {
    totalRunTime1 = 0;
    const data = await IotOpeationFillApi.getAttrs(queryParams)
    attrList.value = data;
    //totalRunTime1 = Number(attrList.value[0].totalRunTime).toFixed(2)
    attrList.value.forEach(function (item,index){
      if(item.name==='累计运行时间'){
        item.name = '当日运转时间'
        totalRunTime1 = Number(item.totalRunTime).toFixed(2)
      }
      item.fillContent = Number(item.fillContent).toFixed(2)
      item.deviceCode = queryParams.deviceCode;
      item.deptId = queryParams.deptId;
      item.deviceId = queryParams.deviceId;
      item.deviceCategoryId = queryParams.deviceCategoryId;
    })

  } finally {
    loading.value = false
  }
}
/** 获取填写信息保存到后台*/
const getFillInfo = async () => {
  try {
    attrList.value.forEach(function (item,index){
      item.pointName = item.name;
      item.createTime = formatTimestamp(JSON.parse(deptId.split(",")[2]));
      item.userId = deptId.split(",")[1];
    })
    const data = attrList.value as unknown as IotOpeationFillVO

    await IotOpeationFillApi.insertLog(data)
    message.success(t('common.createSuccess'))
    // 发送操作成功的事件
    emit('success')
    getList();
  } finally {

  }
}
/**清空填写信息*/
const deleteFillInfo = () =>{
  attrList.value.forEach(function (item, index){
    item.fillContent = '';
  });
}


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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await IotOpeationFillApi.exportIotOpeationFill(queryParams)
    download.excel(data, '运行记录填报.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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

})
</script>
<style scoped>
.back-red{		/* 红色背景 */
  background-color: red;
}
.back-blue{
  background-color: grey;
}
.step-container {
  display: grid;
  grid-template-columns: 220px 1fr;
  gap: 10px;
  height: 100%;
  min-height: 600px;
}

.steps-nav {
  overflow-y: auto;
  padding-right: 15px;
}

.form-wrapper {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.navigation-controls {
  margin-top: 40px;
  text-align: center;
}

.custom-label {
  color: green;
}
::v-deep .el-step__icon {
  background-color: #409eff;
  color: #fff;
  border: 0px;
}
.step-title-wrapper {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  position: relative;
  padding-right: 25px;
}

/* 覆盖步骤条默认样式 */
:deep(.custom-steps) {

/* 调整头部位置 */
.el-step__head {
  top: 3px;
}

/* 标题容器定位 */
.el-step__title {
  display: inline-block;
  margin-left: 10px;
  padding-right: 0;
}

/* 步骤连接线 */
.el-step__line {
  left: 11px;
  background-color: #ebeef5;
}

/* 当前步骤样式 */
.is-process .title-text {
  font-weight: 600;
  color: #409eff;
}

/* 完成状态图标 */
.is-finish .tip-icon {
  color: #67c23a;
}

}
</style>
