<template>
  <div class="table-box">
    <div style="display: flex;flex-direction: column;">

      <div style="flex-grow: 1;height: 66vh;overflow-y: auto;overflow-x: hidden">
        <el-radio-group v-model="radio1">
          <el-radio-button label="自动" :value="1" plain />
          <el-radio-button label="人工" :value="2" plain />
        </el-radio-group>
        <!-- 表格主体 -->
        <div class="table-box" style="margin-top: 20px;height: 57vh">
          <el-table stripe ref="tableRef" :border="true" :data="radio1 === 1 ? certData : certData2" size="small">
            <el-table-column align="left" label="序号" width="45px" :show-overflow-tooltip="true">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <template v-for="item in columns" :key="item">
              <el-table-column v-bind="item" :align="item.align ?? 'left'"
                :reserve-selection="item.type == 'selection'">
                <template #default="scope">
                  <template v-if="item.prop === 'cal_date_i'">
                    <!-- <el-date-picker class="no-border" v-model="scope.row.c" type="date" placeholder="请选择日期" /> -->
                    <div>{{ scope.row.cal_date_i ? formatDate(scope.row.cal_date_i) : '' }}</div>
                  </template>
                  <template v-if="item.prop === 'cal_period'">
                    <!-- <div style="min-height: 20px" @dblclick="editCell(scope.row, 'd')">
                      <el-input v-if="isEditing(scope.row, 'd')" ref="inputRef" v-model="scope.row.d"
                        @blur="saveEdit(scope.row, 'd')" />
                      <span v-else>{{ scope.row.d }}</span>
                    </div> -->
                    {{ scope.row.cal_period }}
                  </template>
                  <template v-if="item.prop === 'operation'">
                    <el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
                      <el-button type="primary" link @click="handleUpdate(scope.row)">
                        <el-icon>
                          <Edit />
                        </el-icon>
                      </el-button>
                    </el-tooltip>
                  </template>
                </template>
              </el-table-column>
            </template>

            <!-- 无数据 -->
            <template #empty>
              <div class="table-empty">
                <slot name="empty">
                  <img src="@/assets/images/notData.png" alt="notData" />
                  <div>暂无数据</div>
                </slot>
              </div>
            </template>
          </el-table>
        </div>
      </div>
      <div class="disposition-bottom">
        <el-button disabled> 取消 </el-button>
        <el-button disabled type="primary" plain> 上一步 </el-button>
        <el-button disabled type="primary"> 下一步 </el-button>
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="formRef" :model="instrumentForm" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="20">
            <el-radio-group v-model="instrumentForm.type" @change="changeTop">
              <template v-if="seTypeList.length > 0">
                <el-radio-button v-for="(item, index) in seTypeList" :key="index" :label="item.name" :value="item.name"
                  plain />
              </template>
              <template v-else>
                <el-radio-button v-for="(item, index) in novalSetypeList" :key="index" :label="item" :value="item"
                  disabled plain />
              </template>
            </el-radio-group>
          </el-col>
        </el-row>
        <!-- <el-row :gutter="20">
          <el-col :span="20" style="margin-top: 10px">
            <el-button type="primary" plain>新增</el-button>
            <el-button plain>删除</el-button>
          </el-col>
        </el-row> -->
        <el-row :gutter="20">
          <el-col :span="20" style="margin-top: 10px">
            <el-radio-group v-model="instrumentForm.element" @change="changeElement">
              <el-radio-button v-for="(item, index) in selectInfo?.list" :key="index" :value="item.cal_condition"
                plain>{{
                  item.cal_condition && item.cal_condition != '' && item.cal_condition != ' ' ? item.cal_condition : 'NA'
                }}</el-radio-button>
            </el-radio-group>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="12">
            <el-form-item label="检定条件" prop="verification">
              <el-input disabled v-model="selectTable.cal_condition" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证书编号" prop="certificate">
              <el-input disabled v-model="selectTable.cal_calsn" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检定员编号" prop="inspector">
              <el-input disabled v-model="selectTable.cal_calman" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检定参数类型" prop="typeParameter" style="display: flex; align-items: center">
              <el-radio-group disabled v-model="selectTable.cal_type">
                <el-radio :value="1" size="large">校准系数</el-radio>
                <el-radio :value="2" size="large">多点校准系数</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" v-if="selectTable.cal_type === 1">
          <el-col :span="12">
            <el-form-item label="校准系数" prop="coefficient">
              <el-input disabled v-model="selectTable.cal_param" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="selectTable.cal_type === 2" class="table-box" style="margin-top: 10px;height: 200px">
          <el-table stripe ref="tableRef" :border="true" :data="selectTable.cal_param_list" size="small">
            <template v-for="item in columns2" :key="item">
              <el-table-column v-bind="item" :align="item.align ?? 'left'" :reserve-selection="item.type == 'selection'"
                :show-overflow-tooltip="true">
                <template v-if="item.prop === 'operation'">
                  <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                    <el-button type="primary" disabled link>
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
            </template>

            <!-- 无数据 -->
            <template #empty>
              <div class="table-empty">
                <slot name="empty">
                  <img src="@/assets/images/notData.png" alt="notData" />
                  <div>暂无数据</div>
                </slot>
              </div>
            </template>
          </el-table>
        </div>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" disabled>取 消</el-button>
          <el-button type="primary" @click="submitForm" disabled>确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
import { defineProps, reactive, ref, onMounted } from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { getQuerCertList, getQueryAllSysItem } from "@/api/modules/allData";
const props = defineProps(['selectData', 'sensorList'])


// 获取检定证书
const certData = ref<any>([]);
const certData2 = ref<any>([]);
const querCert = ref<any>({
  pageSize: 1000,
  pageNum: 1,
})

const stationCal = ref<any>([])
const getCertList = async () => {
  const { data } = await getQuerCertList({ ...querCert.value, asCode: props.selectData?.as_code });
  stationCal.value = data?.list


  certData.value = props.sensorList?.filter(item =>
    item.se_state == 1
  )
  certData.value?.forEach(obj1 => {
    const matchingObj2 = data?.list?.find(obj2 => obj2.se_type === obj1.se_type);
    if (matchingObj2) {
      obj1.cal_sn = matchingObj2.cal_sn;
      obj1.cal_date_i = matchingObj2.cal_date_i;
      obj1.cal_period = matchingObj2.cal_period;
      obj1.next_period = addMonthsToTimestamp(matchingObj2.cal_date_i, matchingObj2.cal_period)
    }else {
      obj1.cal_sn = '';
      obj1.cal_date_i = '';
      obj1.cal_period = '';
      obj1.next_period = ''
    }
  });
  certData2.value = props.sensorList?.filter(item =>
    item.se_state == 2
  )
  certData2.value?.forEach(obj1 => {
    const matchingObj2 = data?.list?.find(obj2 => obj2.se_type === obj1.se_type);
    if (matchingObj2) {
      obj1.cal_sn = matchingObj2.cal_sn;
      obj1.cal_date_i = matchingObj2.cal_date_i;
      obj1.cal_period = matchingObj2.cal_period;
      obj1.next_period = addMonthsToTimestamp(matchingObj2.cal_date_i, matchingObj2.cal_period)
    }else {
      obj1.cal_sn = '';
      obj1.cal_date_i = '';
      obj1.cal_period = '';
      obj1.next_period = ''
    }
  });

}


const changeTop = (val: any) => {
  selectInfo.value = seTypeList.value?.find(obj => obj.name === val);
  // instrumentForm.value.type = selectInfo?.value.name
  instrumentForm.value.element = selectInfo.value?.list[0].cal_condition

  selectTable.value = selectInfo.value?.list[0]
  
}

const changeElement = (val: any) => {
  selectTable.value = selectInfo.value?.list?.find(obj => obj.cal_condition === val);

}

//时间戳转换为指定格式的日期字符串
function formatDate(timestamp) {
  const date = new Date(timestamp * 1000); // 将时间戳转换为毫秒
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 获取指定月份之后的日期
function addMonthsToTimestamp(timestampInSeconds, months) {
  const date = new Date(timestampInSeconds * 1000); // 乘以1000将秒转换为毫秒
  // 例如，设置月份为13会将年份增加1并将月份设置为1
  date.setMonth(date.getMonth() + months);
  // 格式化日期为yyyy-mm-dd字符串
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1，并用padStart确保是两位数
  const day = String(date.getDate()).padStart(2, '0'); // 用padStart确保是两位数
  return `${year}-${month}-${day}`;
}

const radio1 = ref<any>(1)  //检定参数类型



const formRef = ref<any>();
const dialog = reactive<any>({
  visible: false,
  title: '',
  isMode: true
});

const rules = ref<any>(
  {
    verification: [{ required: true, message: "检定条件不能为空", trigger: "blur" }],
    certificate: [{ required: true, message: "证书编号不能为空", trigger: "blur" }],
    inspector: [{ required: true, message: "检定员编号不能为空", trigger: "blur" }],
    typeParameter: [{ required: true, message: "检定参数类型不能为空", trigger: "blur" }],
  }
);

const initFormData = ref<any>(
  {
    type: 'PWS',
    element: '',
    verification: '',
    certificate: '',
    inspector: '',
    typeParameter: '1',
    coefficient: ''

  }
);

const instrumentForm = ref<any>({
  type: 'PWS',
  element: '',
  verification: '',
  certificate: '',
  inspector: '',
  typeParameter: '1',
  coefficient: ''
});

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "新增";
  dialog.isMode = true;
}

/** 修改按钮操作 */

const seTypeList = ref<any>([])
const selectInfo = ref<any>({})
const selectTable = ref<any>({
  cal_condition: '',
  cal_calsn: '',
  cal_calman: '',
  cal_type: 1,
  cal_param: '',
  cal_param_list: [],
})
const list = ref<any>([])
const novalSetypeList = ref<any>(['P'])
const handleUpdate = async (row?: any) => {
  reset();
  list.value = stationCal.value?.filter(obj => obj.se_type === row.se_type);
  const groupedData = list.value?.reduce((acc, item) => {
    const { cal_probeid } = item;
    if (!acc[cal_probeid]) {
      acc[cal_probeid] = [];
    }
    acc[cal_probeid].push(item);
    return acc;
  }, {});


  if (groupedData) {
    seTypeList.value = Object.keys(groupedData).map(key => ({
      name: key,
      list: groupedData[key]
    }));
  }

  seTypeList.value.forEach(item => {
    item.list?.forEach(obj => {
      obj.cal_param_list = obj.cal_param.split(',').map(pair => {
        const [checkKey, changeKey] = pair.split('/');
        return { checkKey, changeKey };
      });
    });
  });
  if (seTypeList.value?.length == 0) {
    if (row.se_type === 100) {
      novalSetypeList.value = allSystem.value.find(item => item.item_key === '19')?.item_value.split('|')
    } else if (row.se_type === 200) {
      novalSetypeList.value = allSystem.value.find(item => item.item_key === '23')?.item_value.split('|')
    } else if (row.se_type === 300) {
      novalSetypeList.value = allSystem.value.find(item => item.item_key === '22')?.item_value.split('|')
    }else if (row.se_type === 1000) {
      novalSetypeList.value = allSystem.value.find(item => item.item_key === '20')?.item_value.split('|')
    } else if (row.se_type === 1300) {
      novalSetypeList.value = allSystem.value.find(item => item.item_key === '21')?.item_value.split('|')
    } else if (row.se_type === 1400) {
      novalSetypeList.value = allSystem.value.find(item => item.item_key === '21')?.item_value.split('|')
    } else {
      novalSetypeList.value = ['P']
    }
  }

  selectInfo.value = seTypeList.value[0]
  instrumentForm.value.type = seTypeList?.value[0]?.name
  instrumentForm.value.element = seTypeList?.value[0]?.list[0].cal_condition
  selectTable.value = seTypeList.value.length > 0 ? seTypeList.value[0]?.list[0] : {
    cal_condition: 'NA',
    cal_calsn: '',
    cal_calman: '',
    cal_type: 1,
    cal_param: '',
    cal_param_list: [],
  }
  
  if (selectTable.value.cal_condition === '' || selectTable.value.cal_condition === ' ') {
    selectTable.value.cal_condition = 'NA'

  }
  // instrumentForm.value = { ...instrumentForm.value, ...seTypeList.value[0].list[0] }


  dialog.visible = true;
  dialog.title = "编辑";
  dialog.isMode = false;
}


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}
/** 表单重置 */
const reset = () => {
  instrumentForm.value = { ...initFormData };
  formRef.value?.resetFields();
}

/** 修改密码提交按钮 */
const submitForm = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      dialog.visible = false;
    }
  });
}



const processTableData = ref([
  {
    a: "超声风传感器",
    b: "",
    c: "",
    d: "11111111111111111",
    e: ""
  },
  {
    a: "超声风传感器",
    b: "",
    c: "",
    d: "11111111111111111",
    e: ""
  }
]);

// 表格配置项
const columns = reactive<ColumnProps[]>([
  { prop: "se_name", label: "检定项目" },
  { prop: "cal_sn", label: "传感器序列号" },
  { prop: "cal_date_i", label: "检定日期" },
  { prop: "cal_period", label: "检定周期(月)" },
  { prop: "next_period", label: "下一次检定日期" },
  { prop: "operation", label: "操作", width: 150, align: 'center' }
]);

const processTableData2 = ref([
  {

  },
  {

  }
]);

// 表格配置项
const columns2 = reactive<ColumnProps[]>([
  { prop: "checkKey", label: "检定值" },
  { prop: "changeKey", label: "修正值" },
  { prop: "operation", label: "操作", width: 150, align: 'center' }
]);

const editingRow = ref<any | null>(null);
const editingField = ref<string | null>(null);
const editCell = (row: any, field: string) => {
  editingRow.value = row;
  editingField.value = field;
};

const isEditing = (row: any, field: string) => {
  return editingRow.value === row && editingField.value === field;
};

const saveEdit = (row: any, field: string) => {
  editingRow.value = null;
  editingField.value = null;
};

const allSystem = ref<any>([])
const getAllSystem = async () => {
  const { data } = await getQueryAllSysItem()
  allSystem.value = data.list

}

onMounted(() => {
  getCertList();
  getAllSystem()
});
</script>

<style scoped>
.table-box {
  height: 100%;
}

::v-deep .no-border .el-input__wrapper {
  box-shadow: 0 0 0 0px !important;
  background-color: #00000000;
}
</style>
