<template>
  <!-- <teleport to=".app-container">  -->
  <ContentWrap :title="title" class="check-record-wrapper" v-loading="pageLoading">
    <!-- 作业指导书自定义附件，显示pdf预览 -->
    <div class="designer-inner">
      <SpreadViewer :initData="editData" ref="editSpreadRecordRef" @saveSuccess="saveSuccessRecord"/>
    </div>
    <div class="operation-inner">
      <div class="btn-list">
        <template v-if="isEdit">
          <el-button type="primary" @click="handleSubmitBefore">提交审核</el-button>
<!--          <el-button type="primary" @click="handleChooseInstrument">选择仪器</el-button>-->
        </template>
        <el-button type="default" plain @click="handleCloseModal">取 消</el-button>
      </div>
      <!-- 智能纠错 -->
      <div class="operation-item">
        <div class="item-header"> 智能纠错 </div>
        <div class="item-content">
          <el-empty v-if="!checkInputList.length" description="暂无纠错内容" :image-size="120" />
        </div>
      </div>
      <!-- 历史版本 -->
      <div class="operation-item">
        <div class="item-header"> 历史版本 </div>
        <div class="item-content">
          <el-empty v-if="!recordVersionList.length" description="暂无版本信息" :image-size="120" />
        </div>
      </div>
    </div>
  </ContentWrap>
  <!-- </teleport> -->
  <SelectModal ref="selectModalRef" @confirm="handleConfirm" />

  <CustomDialog
    ref="customUnitDialogRef"
    title="选择批准人"
    v-model="approvalUserVisible"
    width="650px"
    :dialogAttrs="{ zIndex: 10006 }"
  >
    <el-form ref="formRef" :model="formValueData" :rules="formRules" label-width="135px">
      <el-form-item label="批准人" prop="workInstructionAuditId">
        <el-select v-model="formValueData.workInstructionAuditId" clearable placeholder="请选择">
          <el-option
            v-for="item in optionList.guidebookApproveList"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="approvalUserVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmitUser">确定</el-button>
    </template>
  </CustomDialog>
</template>
<script lang="tsx" setup>
import VuePdfEmbed from 'vue-pdf-embed'
import { BoilerTaskOrderApi } from '@/api/pressure2/boilertaskorder'
import {defineModel, ref} from 'vue'
import SpreadDesigner from '@/components/SpreadDesigner/index.vue'
import { buildFileUrl } from '@/utils'
import axios from 'axios'
import { uploadFile } from '@/api/common/index'
import { getPressureReportTemplateInfo } from '@/api/pressure2/reportTemplate/index'
import { PressureReportType } from '@/utils/constants'
import SelectModal from './selectModal.vue'
import { getStrDictOptions } from '@/utils/dict'
import { SmartTableColumn } from '@/types/table'
import { ElForm } from 'element-plus'
import * as UserGroupApi from '@/api/bpm/userGroup'
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
import { isEmpty } from 'lodash'

import {
  getStandardTemplateInfo
} from '@/api/laboratory/standard/template'
import {DynamicTbValApi} from "@/api/pressure2/dynamictbval"
import {DynamicTbInsApi} from "@/api/pressure2/dynamictbins"
import * as GC from '@grapecity-software/spread-sheets'
import {DynamicTbApi} from "@/api/pressure2/dynamictb";
import {editReport} from "@/utils/reportUtil";
import {DynamicTbColApi} from "@/api/pressure2/dynamictbcol";
import {SpreadViewer} from "@/components/DynamicReport";
import {InitParams} from "@/components/DynamicReport/SpreadInterface";

const { submitOpinionNoticeApproval } = BoilerTaskOrderApi
const userStore = useUserStore()
const userInfo = computed(() => userStore.user)
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  templateId: {
    type: String,
    default: ''
  },
  reportId: {
    type: String,
    default: ''
  },
  orderId: {
    // 任务单ID
    type: String,
    default: ''
  },
  dataJSON: {
    type: String,
    default: ''
  },
  curReportTypeInfo: {
    type: Object,
    default: () => {}
  },
  isCustomFileUrl: {
    type: Boolean,
    default: false
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['success', 'cancel'])
const visible = defineModel('visible', { type: Boolean, default: false })
const pageLoading = ref(true)

const ReportPdfRef = ref()
const rowReportPdfUrl = ref('')

// 编辑器对象
let designer: any = null
const designerRef = ref()

// 关闭弹窗
const handleCloseModal = () => {
  visible.value = false
  emits('cancel')
}

const tempDataSource = ref()
//记录保存 -- 新版本
const confirmSaveParams = ref()

const handleConfirmSave = async()=>{
  const params = unref(confirmSaveParams)
  if(!params.id || !params.reportUrl) return
  const saveResult = await BoilerTaskOrderApi.submitOpinionNoticeApproval(params)
  if (saveResult) {
    //emits('confirm', params.reportUrl)
    emits('success', params)
    handleCloseModal()
  }
}

// 智能纠错
const checkInputList = ref([])
// 版本管理
const recordVersionList = ref([])

const statusDictOptions = getStrDictOptions('pressure_instrument_management_status')
const selectModalRef = ref<InstanceType<typeof SelectModal>>()
type ModalParamsConfig = {
  modalUrl: string
  columns: SmartTableColumn[]
  isSingle: boolean
  modalParams?: any
  keyWord?: string
  modalTitle?: string
}
const openModalConfig: ModalParamsConfig = {
  modalUrl: '/pressure/instrument-management/page',
  columns: [
    {
      type: 'index',
      label: '序号',
      width: 80,
      fieldProps: {
        align: 'center'
      }
    },
    {
      prop: 'status',
      label: '仪器状态',
      fieldProps: {
        align: 'center',
        minWidth: 120
      },
      render: (row: any) => {
        return (statusDictOptions.find((item) => item.value === row.status) || {})?.label || '-'
      }
    },
    {
      prop: 'toolboxNo',
      label: '工具箱编号',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'mgrNo',
      label: '管理编号',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'name',
      label: '设备名称',
      fieldProps: {
        align: 'center',
        minWidth: 150
      }
    },
    {
      prop: 'alias',
      label: '设备别名',
      fieldProps: {
        align: 'center',
        minWidth: 150
      }
    },
    {
      prop: 'calibrationDate',
      label: '校准日期',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'nextCalibrationDate',
      label: '下次校准日期',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'printType',
      label: '打印类型',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'mfgno',
      label: '出厂编号',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'purchaseDate',
      label: '购置日期',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'processor',
      label: '经手人',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'acceotor',
      label: '验收人',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    },
    {
      prop: 'deptName',
      label: '领用部门',
      fieldProps: {
        align: 'center',
        minWidth: 120
      }
    }
  ],
  isSingle: true,
  keyWord: 'name',
  modalTitle: '选择仪器'
}
// 添加仪器关联
const handleChooseInstrument = () => {
  selectModalRef.value?.openModal(openModalConfig)
}

// 将选择的仪器信息和关联的字段进行绑定，然后更新葡萄城页面显示
const handleConfirm = (record: Recordable[]) => {
  const bindingPathSchema = designer && designer?.getData('treeNodeFromJson')
  console.log(designerRef.value?.getDataSource(), 'getDataSource')
  const prepareJson = designerRef.value?.getDataSource() || {}
  if (bindingPathSchema) {
    const currentRow = record[0] || {}
    const result = {}
    for (const key in currentRow) {
      if (!isEmpty(currentRow[key])) {
        result[key] = currentRow[key]
      }
    }
    const dataSource = { ...prepareJson, ...result }

    // console.log('dataSource', dataSource)
    // 设置数据源的默认值
    designerRef.value.newSetDataSource(bindingPathSchema, dataSource)
  }
}

// 选择审核人
const formRef = ref<InstanceType<typeof ElForm>>()
const formValueData = ref<Recordable>({})
const formRules = reactive({
  workInstructionAuditId: [{ required: true, message: '请选择批准人', trigger: 'change' }]
})

const optionList = reactive<{
  guidebookApproveList: Recordable[]
}>({
  guidebookApproveList: []
})
const approvalUserVisible = ref(false)
// 获取审核人信息
const getGuidebookApproveList = async () => {
  try {
    const { workInstructionAuditId } = await UserApi.getApprovalDetail({})
    formValueData.value = {
      workInstructionAuditId
    }
    optionList.guidebookApproveList = await UserGroupApi.getUserGroupUserList({
      category: 500,
      status: 0
    })
    approvalUserVisible.value = true
  } catch (error) {}
}
const handleSubmitUser = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      approvalUserVisible.value = false
      //await handleSaveNew()
      await handleConfirmSave()
    }
  })
}

const handleSubmitBefore = async () => {

  try {
    await editSpreadRecordRef.value?.handleSave()
  } catch (error) {
    console.error('保存数据失败:', error)
    ElMessage.error('保存数据失败，请重试')
    return
  }

  await getGuidebookApproveList()

}


const editData=ref<InitParams>(
  {
    templateId: '',
    refId: '',
    refName:'',
    insId:'',
    opType: 0, // 0:excel,1: pdf
  });
const editSpreadRecordRef=ref();
const saveSuccessRecord = async (data)=>{
  const dataJson = !data.dataSource ? '' : JSON.stringify(data.dataSource)
  confirmSaveParams.value.prepareJson = dataJson
}
const editPreview=()=>{

  editData.value.templateId = props.templateId;
  editData.value.refId = props.reportId;
  if (props?.isEdit){
    editData.value.opType = 0;
  }else{
    editData.value.opType = 1;
  }


  editSpreadRecordRef.value?.reloadView();

  confirmSaveParams.value = {
      id: props.reportId,
      reportUrl: props.reportId,
      auditUserIds: [formValueData.value.workInstructionAuditId]
  }

  pageLoading.value = false

  console.log('editDataPreview', editData.value)
}

onMounted(() => {
  editPreview()
})

</script>

<style lang="scss" scoped>
:deep(.app-container) {
  position: relative;
}
.check-record-wrapper {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 2000;
  :deep(.el-card__body) {
    display: flex;
    justify-content: space-between;
    align-items: stretch;
    height: calc(100% - 58px);
  }
  :deep(.spread-designer-container) {
    height: calc(
      100vh - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height) - 64px
    );
    padding: 0;
    border: 1px solid var(--el-border-color);
    border-right-width: 0px;
  }
  .designer-inner {
    width: calc(100% - 440px);
    flex: 1;
    position: relative;
  }
  .operation-inner {
    display: flex;
    flex-direction: column;
    gap: 10px;
    height: 100%;
    flex-basis: 440px;
    padding: 7px 10px 20px 10px;
    border: 1px solid var(--el-border-color);
    background-color: #fff;
    box-sizing: border-box;
    overflow: hidden;
    .btn-list {
      padding: 5px 0 2px;
    }
    .version-box {
      padding: 8px 0 12px;
    }
    .operation-item {
      position: relative;
      max-height: calc(100% / 3);
      overflow: hidden;
      .item-header {
        position: sticky;
        left: 0;
        top: 0;
        z-index: 1000;
        width: 100%;
        height: 28px;
        padding-left: 20px;
        font-size: 16px;
        line-height: 28px;
        color: #fff;
        background: #fff url(@/assets/imgs/pressure/my-task-detail-operation-bg.png) no-repeat left
          top;
        background-size: 100% 28px;
      }
      .item-content {
        // height: calc(100% - 48px);
        height: auto;
        padding: 10px 0;
        font-size: 14px;
        overflow-y: auto;
        overflow-x: hidden;
        box-sizing: content-box;
        .el-empty {
          width: 100%;
          height: 150px;
          padding: 0;
          box-sizing: border-box;
        }
      }
      &:last-child {
        max-height: unset;
        flex-grow: 1;
        .item-content {
          height: calc(100% - 48px);
        }
      }
      :deep(.smart-table-inner .toolbar) {
        margin: 0 !important;
      }
      .error-item {
        display: flex;
        align-items: center;
        padding: 7px 10px;
        color: #41475c;
        border: 1px solid var(--el-border-color);
        border-width: 1px 0 1px 0;
        background-color: #f5f5fa;
        .el-icon {
          margin-right: 6px;
        }
        &:nth-child(n + 1) {
          margin-top: -1px;
        }
        &:nth-child(even) {
          background-color: #fff;
        }
      }
    }
  }
}
</style>
