<template>
  <div>
    <Dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      :width="dialogWidth"
      :close-on-click-modal="false"
      :vLoading="formLoading"
    >
      <div style="max-height: 80vh; overflow-y: auto; padding: 0px 20px">
        <Form
          ref="formMainRef"
          :rules="rules"
          :schema="formSchema"
          :is-col="true"
          @onChange="onChange"
        />
        <div class="small-title">包装列表</div>
        <div style="border:1px solid #dedede;margin-bottom:20px;display: flex;">
          <TableForm
            ref="tableFormRef"
            style="width:100%;"
            :maxHeight = "490"
            :tableFields="tableSchemas.tableFormColumns"
            :tableFormRules="tableFormRules"
            :tableData="data.packageList"
            :isShowButton="false"
            :isShowReduceButton="false"
            @inputStringBlur="tableFormBlur"
          />
        </div>
      </div>
      <template #footer>
        <ButtonBase :Butttondata="Butttondata" @button-base-click="buttonBaseClick" />
      </template>
    </Dialog>
    <SearchTable ref="searchTableRef" @searchTableSuccess="searchTableSuccess" />
  </div>
</template>

<script setup lang="ts">44
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import { getCurrentInstance } from 'vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { SearchTable } from '@/components/SearchTable'
import * as InspectionRecordMainApi from '@/api/qms/inspectionRecord/inspectionRecordMain'
import * as InspectionRecordPackageApi from '@/api/qms/inspectionRecord/InspectionRecordPackage/InspectionRecordPackage'

const { proxy } = getCurrentInstance()

const message = useMessage() // 消息弹窗

const props = defineProps({
  // 显示窗口宽度设置
  basicFormWidth: {
    type: String,
    default: ''
  },
  // 底部按钮集合
  footButttondata: {
    type: Array,
    required: false,
    default: null
  },
  // 表单，列表 相关信息
  formAllSchemas: {
    type: Object,
    required: true,
    default: null
  },
  // 校验rules
  rules: {
    type: Object,
    required: true,
    default: null
  },
  // 包装 列表 相关信息
  tableAllSchemas: {
    type: Array,
    required: true,
    default: null
  },
  tableFormRules: {
    type: Array,
    required: true,
    default: null
  },
})
const { t } = useI18n() // 国际化

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const dialogWidth = ref()
const formSchema = ref(props.formAllSchemas?.formSchema)
const tableSchemas = ref(props.tableAllSchemas)
const tableFormRules = ref(props.tableFormRules)
const formMainRef = ref()

const data = ref({
  code: '',
  itemCode: '',
  version: '',
  testTypeCode: '',
  programmeTemplateCode: '',
  splitRule: '',
  aql: '',
  inspectionLevel: '',
  effectiveDate: '',
  expirationDate: '',
  available: 'TRUE',
  subList: []
})

if (props.basicFormWidth) {
  dialogWidth.value = props.basicFormWidth + '%'
} else {
  dialogWidth.value = props.isBusiness ? '60%' : '40%'
}

/** 打开弹窗 */
const open = async (type: string, row?: any, masterParmas?: any, titleName?: any) => {
  dialogTitle.value = t('action.applyDecision')
  formType.value = type
  if (row) {
    data.value = JSON.parse(JSON.stringify(row))
    data.value.packageList = await InspectionRecordPackageApi.getInspectionRecordPackageList(row.id)
    data.value.packageList.forEach(item=>{
      item.qualifiedAmount = item.qualifiedAmount?item.qualifiedAmount:0
      item.noQualifiedAmount = item.noQualifiedAmount?item.noQualifiedAmount:0
      item.destroyAmount = item.destroyAmount?item.destroyAmount:0
      item.frozenAmount = item.frozenAmount?item.frozenAmount:0
    })
    dialogVisible.value = true
    tableSchemas.value.tableFormColumns.map(item=>{
      item.tableForm.disabled = true
    })
    // 评估代码值是1，接收时候，使用决策下拉列表是全部合格
    if(row.estimateCode == 1){
      data.value.useDecision = '1'
    }else{
      data.value.useDecision =''
    }
    // 全部合格时合格数量==数量
    if(data.value.useDecision == 1){
      data.value.packageList.forEach(item=>{
        item.qualifiedAmount = item.amount
      })
    }
    // 让步接收和部分合格
    else if(data.value.useDecision  == 2 || data.value.useDecision  == 6){
      tableSchemas.value.tableFormColumns.map(item=>{
        if(item.field == 'noQualifiedAmount'){
          item.tableForm.disabled = false
        }else{
          item.tableForm.disabled = true
        }
      })
    }
    // 全不合格只能输入不合格数量
    else if(data.value.useDecision  == 3){
      data.value.packageList.forEach(item=>{
        item.noQualifiedAmount = item.amount
      })
    }
    else if(data.value.useDecision  == 4){
      data.value.packageList.forEach(item=>{
        item.frozenAmount = item.amount
      })
    }
    
    nextTick(() => {
      formMainRef.value.setValues( data.value)
    })
  } 
  dialogVisible.value = true
}
defineExpose({ open, dialogVisible, formLoading }) // 提供 open 方法，用于打开弹窗

// console.log(11,tableAllSchemas.value.tableFormColumns)
// 传递给父类
const emit = defineEmits([
  'onChange',
  'submitForm'
])
/** 弹窗按钮 */
let Butttondata: any = []
if (props.footButttondata) {
  Butttondata = props.footButttondata
} else {
  Butttondata = [
    defaultButtons.formSaveBtn(null), // 保存
    defaultButtons.formCloseBtn(null) // 关闭
  ]
}
const onChange = (field, cur)=>{
  if(field=='useDecision'){
    tableSchemas.value.tableFormColumns.map(item=>{
      item.tableForm.disabled = true
    })
    data.value.packageList.forEach(item=>{
        item.qualifiedAmount =0
        item.noQualifiedAmount =0
        item.destroyAmount =0
        item.frozenAmount =0
      })
    // 全部合格时合格数量==数量
    if(cur == 1){
      data.value.packageList.forEach(item=>{
        item.qualifiedAmount = item.amount
      })
    }
    // 全不合格只能输入不合格数量
    else if(cur == 2 || cur == 6){
      data.value.packageList.forEach(item=>{
        item.qualifiedAmount = item.amount
      })
      tableSchemas.value.tableFormColumns.map(item=>{
        if(item.field == 'noQualifiedAmount'){
          item.tableForm.disabled = false
        }else{
          item.tableForm.disabled = true
        }
      })
    }
    // 全不合格只能输入不合格数量
    else if(cur == 3){
      data.value.packageList.forEach(item=>{
        item.noQualifiedAmount = item.amount
      })
    }
    else if(cur == 4){
      data.value.packageList.forEach(item=>{
        item.frozenAmount = item.amount
      })
    }
  }
}
// 失去焦点
const tableFormBlur = (field, val,row)=>{
  if( row.amount < val){
    row.noQualifiedAmount = row.amount
    row.qualifiedAmount = 0
  }else{
    row.qualifiedAmount = row.amount - val
    row.qualifiedAmount = row.qualifiedAmount.toFixed(6)
  }
  
}
const buttonBaseClick = (val) => {
  // 保存
  if (val == 'save') {
    submitForm()
  }
  // 关闭
  else if (val == 'close') {
    dialogVisible.value = false
  }
}
const tableFormRef = ref()
const submitForm = async () => {
  try {
    const elForm = unref(formMainRef)?.getElFormRef()
    // 校验表单
    if (!elForm) return
    const valid = await elForm.validate()
    if (!valid) return
    // 校验包装列表
    const validateForm1 = await tableFormRef.value.validateForm()
    if (!validateForm1) return
      const data1 = unref(formMainRef)?.formModel
      data.value.useDecision = data1.useDecision
    if(data1.useDecision == 2 || data1.useDecision == 6){
      if(data.value.packageList.length>0){
        let isBol = data.value.packageList.filter(cur=>parseFloat(cur.qualifiedAmount)+parseFloat(cur.noQualifiedAmount)!=parseFloat(cur.amount))
        console.log(isBol)
        if(isBol&&isBol.length>0){
          message.error(`合格数量和不合格数量总和不等于数量`)
          return
        }
      } 
    }
    if (formType.value == 'create') {
      // 主子表——提交请求
      emit('submitForm', formType.value, data.value)
    } else {
      // 编辑/执行
      emit('submitForm', formType.value, data.value)
    }
  } catch {
    console.log(111)
  }
}
</script>
<style scoped>
.small-title {
  font-weight: bold;
  padding: 0px 10px 10px;
  color: #1a8bfc;
  font-size: 16px;
}
</style>
<style>
.el-tabs--left .el-tabs__header.is-left {
  min-height: 700px !important;
  min-width: 150px !important;
}
.el-tabs--left.el-tabs--border-card .el-tabs__item.is-left {
  min-width: 120px !important;
}
</style>
