<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 class="custom-label1" 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="t('operationFillForm.team')" class="custom-label1">
                  <span style="text-decoration: underline;">
                    {{item.orgName}}
                  </span>
                </el-form-item>
                <el-row :gutter="20">
                  <el-col
                    v-for="(item,index) in attrList1"
                    :key="index"
                    :span="4"
                  >
                    <el-form-item :label='item.name' class="custom-label1">
                  <span style="text-decoration: underline;">
                  {{item.totalRunTime}}h
                  </span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!--                <el-form-item :label="t('operationFillForm.sumTime')" class="custom-label1">
                                  <span style="text-decoration: underline;">
                                  {{totalRunTime1}}h
                                  </span>
                                </el-form-item>-->
              </el-form>
            </div>
            <div v-for="(item,index) in attrList" :key="index">
              <el-form-item :label='item.name' prop="deviceId"  >
                <el-input
                  v-if="item.isCollection===1||fillStatus === '1'"
                  v-model="item.fillContent"
                  clearable
                  style="width: 200px"
                  disabled
                />
                <el-input
                  v-else
                  v-model="item.fillContent"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
            </div>
            <el-form-item>
              <el-button type="primary" @click="getFillInfo" v-show="showStatus">{{t('operationFillForm.confirm')}}</el-button>
              <el-button type="info" @click="deleteFillInfo" v-show="showStatus">{{t('operationFillForm.cancel')}}</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";
import { ElMessage } from 'element-plus'
import moment from 'moment';
import { format } from 'date-fns';
import {cx} from "@fullcalendar/core/internal-common";
/** 运行记录填报 列表 */
defineOptions({ name: 'IotOpeationFilll' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const loading = ref(true) // 列表的加载中
const { params, name } = useRoute() // 查询参数
const orderId = params.id
const deviceId = params.deviceid
const deptId = params.deptid
const createtime = params.createtime
const list = ref<IotOpeationFillVO[]>([]) // 列表的数据
const attrList = ref<IotOpeationFillVO[]>([]) // 非累计属性集合
const attrList1 = ref<IotOpeationFillVO[]>([]) // 累计属性集合
const total = ref(0) // 列表的总页数
const arry1 =ref([]);
let totalRunTime1: string = '123'
let fillStatus = params.status


let showStatus = true;
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,
  deviceId:undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
let cxStatus = true;

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



const showComponent = () => {
  if(JSON.parse(fillStatus)=== 1){
    showStatus = false;
  }
};


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.orderId = orderId
    queryParams.deviceId = deviceId
    const data = await IotOpeationFillApi.getIotOrderPage(queryParams);
    list.value = data;
    // if(cxStatus){
    if (list.value){
      queryParams.deviceCategoryId = list.value[0].deviceCategoryId
      queryParams.deptId = list.value[0].deptId;
      queryParams.deviceCode = list.value[0].deviceCode;
      queryParams.deviceName = list.value[0].deviceName;
      queryParams.deviceId = list.value[0].deviceId;
    }

    // }
    getAttrList();

  } finally {
    loading.value = false
  }
}
function formatTimestamp(timestamp) {
  return moment.unix(timestamp/1000).format('YYYY-MM-DD');

}

/** 搜索按钮操作 */
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 {
    queryParams.createTime = formatTimestamp(createtime);
    const data = await IotOpeationFillApi.getAttrs(queryParams)
    attrList.value = data[0].nonSumList;
    attrList1.value = data[0].sumList;
    attrList.value.forEach(function (item,index){
      /*if(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;
    })
    attrList1.value.forEach(function (item,index){
      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 = attrList.value.concat(attrList1.value)

    attrList.value.forEach(function (item,index){
      item.pointName = item.name;
      item.createTime = formatTimestamp(JSON.parse(deptId.split(",")[2].substring(0,10)));
      item.userId = deptId.split(",")[1];
      item.id = deptId.split(",")[3];
    })
    const data = attrList.value as unknown as IotOpeationFillVO
    await IotOpeationFillApi.insertLog(data)
    message.success(t('common.createSuccess'))
    // 发送操作成功的事件
    emit('success')
    cxStatus = false;
    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()
  showComponent()
})
</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 {
  font-weight: 1000;
  font-size: 17px;
  padding: 0 10px;
  color: forestgreen;
}
.custom-label1 {
  font-weight: 1000;
  font-size: 17px;
  padding: 0 10px;
}
::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;
  }

}

.horizontal-container {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  gap: 20px; /* 项目间距 */
}

.form-item-container {
  flex: 1; /* 等宽分布 */
  min-width: 200px; /* 最小宽度防止挤压 */
}
</style>
