<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
            :class="['custom-label', { 'has-border': item.deviceName === '生产日报' }]"
            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', { 'has-border': item.deviceName === '生产日报' }]"
                    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" class="scrollable-form">
            <div style="margin-left: 24px">
              <el-form class="demo-form-inline" :inline="true">
                <el-form-item :label="t('common.createTime')" class="custom-label1">
                  <span style="text-decoration: underline;">
                    {{createTime}}
                  </span>
                </el-form-item>
                <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="24"
                  >
                    <el-form-item :label='item.name' class="custom-label1">
                      <span style="text-decoration: underline;">
                      {{item.totalRunTime}}
                      </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" style="margin-left: 24px">
              <!-- 添加提示文字 -->
              <div v-if="item.isCollection===1" class="plc-tip">
                <el-alert
                  :title="t('operationFillForm.alert')"
                  type="warning"
                  :closable="false"
                  center
                  show-icon
                  style="width: 320px;"
                />
              </div>
                <el-form-item :label='item.name' prop="deviceId"  label-position="top">
                  <div v-if="fillStatus === '1'">

                    <el-select
                      disabled
                      v-model="item.fillContent"
                      v-if="item.type === 'enum' && item.description !== null"
                      style="width: 200px">
                      <el-option
                        v-for="dict in getIntDictOptions(item.description)"
                        :key="dict.label"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <el-input
                      v-else
                      v-model="item.fillContent"
                      clearable
                      style="width: 200px; margin-right: 10px"
                      disabled
                    />
                  </div>


                    <el-input
                      v-else-if="item.type === 'textarea'"
                      v-model="item.fillContent"
                      type="textarea"
                      clearable
                      style="width: 200px"
                    />
                    <el-select  v-model="item.fillContent"
                                clearable
                                v-else-if="item.type === 'enum' && item.description !== null"
                                style="width: 200px"
                                filterable>
                      <el-option
                        v-for="dict in getIntDictOptions(item.description)"
                        :key="dict.label"
                        :label="dict.label"
                        :value="dict.value"
                      />
                    </el-select>
                    <el-input
                      v-else
                      v-model="item.fillContent"
                      clearable
                      style="width: 200px"
                      :placeholder="item.type === 'double' ? t('operationFillForm.enterNumber') : t('operationFillForm.enterContent')"
                      @input="handleInput(item)"
                      :maxlength="item.type === 'double' ? calculateMaxLength(item) : undefined"
                    />
                </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('operationFill.clear')}}</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";
import { DICT_TYPE, getIntDictOptions} from '@/utils/dict'

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

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 attrList1 = ref<IotOpeationFillVO[]>([]) // 累计属性集合
const attrList2 = ref<IotOpeationFillVO[]>([]) // 属性集合
const total = ref(0) // 列表的总页数
const arry1 =ref([]);
let totalRunTime1: string = '123'
let fillStatus = params.id.split(",")[4];
let createTime = formatTimestamp(JSON.parse(deptId.split(",")[2].substring(0,10)));
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,
  threshold:undefined,
  defaultValue:undefined,
  isSum: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 calculateMaxLength = (item: any) => {
  if (item.type !== 'double' || !item.threshold) return undefined;

  const max = parseFloat(item.threshold);
  if (isNaN(max)) return undefined;

  // 整数部分长度 + 可能的小数点 + 两位小数
  return max.toString().length + (max.toString().includes('.') ? 0 : 3);
};

// 处理输入事件，实时限制输入格式和最大值
const handleInput = (item: any) => {
  if (item.type === 'double') {
    // 保存原始值用于后续比较
    const originalValue = item.fillContent;

    // 1. 格式验证：只允许数字和小数点
    item.fillContent = item.fillContent.replace(/[^\d.]/g, '');
    // 确保只有一个小数点
    item.fillContent = item.fillContent.replace(/\.{2,}/g, '.');
    // 确保小数点不在开头
    item.fillContent = item.fillContent.replace(/^\./g, '');
    // 限制小数位数为两位
    item.fillContent = item.fillContent.replace(/(\d+)\.(\d{2}).*/, '$1.$2');

    // 2. 最大值验证
    if (item.threshold) {
      const value = parseFloat(item.fillContent);
      const max = parseFloat(item.threshold);

      if (!isNaN(value) && !isNaN(max) && value > max) {
        // 输入值超过阈值时，恢复到修改前的值
        item.fillContent = originalValue.replace(/[^\d.]/g, '')
          .replace(/\.{2,}/g, '.')
          .replace(/^\./g, '')
          .replace(/(\d+)\.(\d{2}).*/, '$1.$2');

        // 如果修正后的值仍然超过阈值，则设置为最大值
        if (parseFloat(item.fillContent) > max) {
          item.fillContent = max.toString();
        }

        // 显示提示信息（使用节流避免频繁提示）
        throttle(() => {
          ElMessage.warning(t('operationFillForm.exceedMax', { max }));
        }, 1000)();
      }
    }
  }
};

// 简单的节流函数，避免提示信息过于频繁
const throttle = (fn: Function, delay: number) => {
  let lastTime = 0;
  return function(...args: any[]) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
};

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


/** 查询列表 */
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].substring(0,10)));
    queryParams.orderId = deptId.split(",")[3];
    const data = await IotOpeationFillApi.getIotOpeationFillPage(queryParams);
      list.value = data;
      if(cxStatus){
        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) {
  const date = new Date(timestamp*1000);
  return moment.unix(timestamp).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 方法，用于打开弹窗
let devName = "";
const openFill = (deviceCategoryId?:number,deviceId?:number,deptId?:number,deviceName?:string,deviceCode?:string) =>{
  queryParams.deviceCategoryId = deviceCategoryId;
  queryParams.deptId = deptId;
  queryParams.deviceCode = deviceCode;
  queryParams.deviceName = deviceName;
  if(queryParams.deviceName=='生产日报'){
    devName = '生产日报';
  }
  queryParams.deviceId = deviceId;
  getAttrList();
}


const getAttrList = async () => {
  loading.value = true
  try {
    queryParams.createTime = formatTimestamp(JSON.parse(deptId.split(",")[2].substring(0,10)));
    const data = await IotOpeationFillApi.getAttrs(queryParams)

    attrList.value = data[0].nonSumList;
    attrList1.value = data[0].sumList;
    attrList.value.forEach(function (item,index){
      if(item.fillContent!=''&& item.fillContent !== null){
        // 尝试将字符串转换为数字
        const num = Number(item.fillContent);

        // 检查是否是有效的数字
        if (!isNaN(num)) {
          // 检查是否包含小数
          if (item.fillContent.includes('.')) {
            // 保留两位小数
            item.fillContent = Number(num.toFixed(2));
          } else {
            // 转换为整数
            item.fillContent = Math.floor(num);
          }
        }
        // 如果不是有效的数字，则保持原文本不变
      }
      item.deviceCode = queryParams.deviceCode;
      item.deptId = queryParams.deptId;
      item.deviceId = queryParams.deviceId;
      item.deviceCategoryId = queryParams.deviceCategoryId;
      item.modelId = item.id;
      console.log(item.fillContent)
    })
    attrList1.value.forEach(function (item,index){
      item.deviceCode = queryParams.deviceCode;
      item.deptId = queryParams.deptId;
      item.deviceId = queryParams.deviceId;
      item.deviceCategoryId = queryParams.deviceCategoryId;
      item.modelId = item.id;
    })
  } finally {
    loading.value = false
  }

}
/** 获取填写信息保存到后台*/
const getFillInfo = async () => {
  try {

    if(devName!='生产日报'){
      // 检查必填字段
      const emptyFields = attrList.value.filter(item => {
        // 只检查非disabled的字段
        return !(item.isCollection===1||fillStatus === '1') &&
          (item.fillContent === undefined || item.fillContent === '');
      });

      if (emptyFields.length > 0) {
        ElMessage.error(t('operationFillForm.fill'));
        return;
      }
    }


    attrList2.value = attrList.value.concat(attrList1.value)

    attrList2.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 = attrList2.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>

.scrollable-form {
  /* 设置最大高度，超过这个高度会出现滚动条 */
  max-height: 500px; /* 根据你的需求调整 */
  /* 超出部分显示垂直滚动条 */
  overflow-y: auto;
  /* 可选：添加内边距和边框美化 */
  padding: 16px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}

/* 可选：美化滚动条 */
.scrollable-form::-webkit-scrollbar {
  width: 6px;
}

.scrollable-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.scrollable-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.scrollable-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}



.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;
}
.has-border {
  border: 2px solid #333; /* 加粗到2px，使用深灰色#333让边框更清晰 */
  padding: 3px 8px; /* 适当增加内边距，避免文字太贴近边框 */
  border-radius: 2px; /* 轻微圆角，可选 */
  font-size: 20px;
}
::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; /* 最小宽度防止挤压 */
}
/* 新增日报填报项的边框样式 */
.report-border {
  border: 2px solid #42b983; /* 使用Vue标志性的绿色边框 */
  padding: 2px 4px;
  border-radius: 4px;
}

</style>
