<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">
        <el-steps style="width: 100%" :active="active" align-center>
          <el-step title="选择质量通知类型" />
          <el-step title="质量通知" />
          <el-step title="质量物料批次" />
        </el-steps>
        <NotaicType v-show="active == 0" ref="notaicTypeFrom" :data='data' :disabled='disabled' @changeType="changeType"/>
        <qualityNotice v-show="active == 1" ref="qualityNoticeFrom" :data='data' :type="data?.type||1" :disabled='disabled' />
        <qualityBatch v-show="active == 2" ref="qualityBatchFrom" :subListData='data.subList' :number='data.number' :disabled='disabled'/>
      </div>
      <template #footer>
        <el-button @click="prov" type="primary" v-if="active != 0">上一步</el-button>
        <el-button @click="next" type="primary" v-if="active != 2">下一步</el-button>
        <ButtonBase :Butttondata="Butttondata" @button-base-click="buttonBaseClick" />
      </template>
    </Dialog>
  </div>
</template>
<script setup lang="ts">
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import { getCurrentInstance } from 'vue'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as qualityNoticeApi from '@/api/qms/qualityNotice'
import NotaicType from './components/notaicType.vue'
import qualityNotice from './components/qualityNotice.vue'
import qualityBatch from './components/qualityBatch.vue'
const { proxy } = getCurrentInstance()
const message = useMessage() // 消息弹窗
const props = defineProps({
  // 显示窗口宽度设置
  basicFormWidth: {
    type: String,
    default: ''
  },
  // 检验特性表单，列表 相关信息
  formAllSchemasFeatures: {
    type: Object,
    required: true,
    default: null
  },
  // 检验工序表单，列表 相关信息
  formAllSchemasProcess: {
    type: Object,
    required: true,
    default: null
  },
  // 检验模板表单，列表 相关信息
  formAllSchemasMain: {
    type: Object,
    required: true,
    default: null
  },
  // 底部按钮集合
  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
  },
  type: {
    type: Number,
    default: 0
  }
})
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 formMainRef = ref()
const formFeaturesRef = ref()

const data = ref({
  type:1,
  subList: []
})
const active = ref(0)
const notaicTypeFrom = ref('')
const qualityNoticeFrom = ref('')
const qualityBatchFrom = ref('')


const dialogVisibleName = ref(false)
const nameForm = ref({
  name: ''
})
const nameRef = ref()
if (props.basicFormWidth) {
  dialogWidth.value = props.basicFormWidth + '%'
} else {
  dialogWidth.value = props.isBusiness ? '60%' : '40%'
}
const rules = ref({
  ...props.rules
})
const disabled = ref(false)
/** 打开弹窗 */
const open = async (type: string, row?: any, masterParmas?: any, titleName?: any) => {
  if (titleName) {
    dialogTitle.value = t('action.' + titleName)
  } else {
    dialogTitle.value = t('action.' + type)
  }
  // 详情设置不可输入
  disabled.value=false
  if(type == 'detail'){
    disabled.value = true
  }
  formType.value = type
  active.value =0
  if (row) {
    data.value = JSON.parse(JSON.stringify(row))
    data.value =  await qualityNoticeApi.qualityNoticeDetail(row.id)
    dialogVisible.value = true
  } else {
    data.value = {
      type:1,
      subList: []
    }
  }
  dialogVisible.value = true
}
defineExpose({ open, dialogVisible, formLoading }) // 提供 open 方法，用于打开弹窗

const buttonBaseClick = (val) => {
  // 保存
  if (val == 'save') {
    submitForm()
  }
  // 关闭
  else if (val == 'close') {
    dialogVisible.value = false
  }
}
// 下一步

// 传递给父类
const emit = defineEmits(['submitForm', 'searchTableSuccess'])
const validateForm = (formRef) => {
  // console.log(TableBaseForm_Ref.value)
  let _lists = formRef?.map((v) => v.validate())
  return Promise.all(_lists)
    .then(() => {
      return true
    })
    .catch(() => {
      return false
    })
}

const tableFormRef = ref()
const submitForm = async () => {
  // qualityBatchFrom.value.qualityBatchFrom
  if(data.value.type == 1){
    data.value.q1 = notaicTypeFrom.value.q1
    delete data.value.q2
    delete data.value.q3
  }else if(data.value.type == 2){
  data.value.q2 = notaicTypeFrom.value.q2
    delete data.value.q1
    delete data.value.q3

  }else if(data.value.type == 3){
  data.value.q3 = notaicTypeFrom.value.q3
    delete data.value.q1
    delete data.value.q2

}

  data.value.subList = qualityBatchFrom.value.subList
  if(data.value.subList.length==0){
    message.error('请填写质量物料批次')
    return;
  }
   const validateForm1 = await validateForm(qualityBatchFrom.value.qualityBatchFrom)
   console.log(validateForm1)
  const isBol =  data.value.subList.some(cur=>{
    return cur.packageList.length == 0 || cur.taskList.length == 0|| cur.defectList.length == 0
   })
   if(isBol){
    message.error('物料批次中包装,任务,缺陷没有填写完全')
    return;
  }
  try {
    if (formType.value == 'create') {
      // 主子表——提交请求
      emit('submitForm', formType.value, data.value)
    } else {
      // 编辑/执行
      emit('submitForm', formType.value, data.value)
    }
  } catch {
    console.log(111)
  }
}
const changeType = (e)=>{
  data.value.type = e
}
/** 弹窗按钮 */
let Butttondata: any = []
if (props.footButttondata) {
  Butttondata = props.footButttondata
} else {
  Butttondata = [
    defaultButtons.formCloseBtn(null) // 关闭
  ]
}

const searchTableRef = ref()
const opensearchTable = (
  formField,
  searchField,
  searchTitle,
  searchAllSchemas,
  searchPage,
  searchCondition,
  multiple,
  type,
  row
) => {
  const _searchCondition = {}
  // 判断查询条件中，是否存在指向主表的数据
  if (searchCondition && searchCondition.length > 0) {
    // 转换筛选条件所需
    let filters: any[] = []
    for (var i = 0; i < searchCondition.length; i++) {
      // searchCondition.forEach((item) => {
      // 查询条件为主表某字段，需要赋值主表数据，数据来源是详情的，赋值需要从row中获取
      if (searchCondition[i].isMainValue) {
        _searchCondition[searchCondition[i].key] = formRef.value.formModel[searchCondition[i].value]
          ? formRef.value.formModel[searchCondition[i].value]
          : props.detailData
          ? props.detailData[searchCondition[i].value]
          : row
          ? row[searchCondition[i].value]
          : ''
        // 是否含有空参数情况
        let isNull = false
        if (
          _searchCondition[searchCondition[i].key] == '' ||
          _searchCondition[searchCondition[i].key] == undefined
        ) {
          isNull = true
        }
        if (isNull) {
          message.warning(
            searchCondition[i].message ? searchCondition[i].message : '前置条件未选择！'
          )
          return
        }
      } else {
        // 扩展 转换为筛选条件进行查询
        if (searchCondition[i].isSearch) {
          filters.push({
            action: searchCondition[i].action,
            column: searchCondition[i].key,
            value: searchCondition[i].value
          })
        } else {
          _searchCondition[searchCondition[i].key] = searchCondition[i].value
        }
      }
    }
    if (filters.length > 0) {
      _searchCondition.isSearch = true
      _searchCondition.filters = filters
    }
  }
  const _searchTableTitle = searchTitle
  const _searchTableAllSchemas = searchAllSchemas
  const _searchTablePage = searchPage
  searchTableRef.value.open(
    _searchTableTitle,
    _searchTableAllSchemas,
    _searchTablePage,
    formField,
    searchField,
    multiple,
    type,
    row,
    _searchCondition
  )
}
// 弹层确定返回所选数据
// val ： 弹层列表row 数据
const searchTableSuccess = async (formField, searchField, val, type, row) => {
  

  // emit('searchTableSuccess', formField, searchField, val, formRef.value, type, row)
}

const next = () => {
  if (active.value == 2) return
  if (active.value == 0) {
    if (notaicTypeFrom.value.type == 1) {
      if(!props.disabled){
        notaicTypeFrom.value.formRef1.validate((valid) => {
          if (valid) {
            active.value++
          } else {
            console.log('error submit!')
            return false
          }
        })
      }
    } else if (notaicTypeFrom.value.type == 2) {
      if(!props.disabled){
        notaicTypeFrom.value.formRef2.validate((valid) => {
          if (valid) {
            active.value++
          } else {
            return false
          }
        })
      }
    } else if (notaicTypeFrom.value.type == 3) {
      if(!props.disabled){
        notaicTypeFrom.value.formRef3.validate((valid) => {
          if (valid) {
            active.value++
          } else {
            console.log('error submit!')
            return false
          }
        })
      }
    }
  }else if (active.value == 1) {
    if(!props.disabled){
      qualityNoticeFrom.value.formRef.validate((valid) => {
        if (valid) {
             // 要求开始时间应小于要求结束时间
          if (qualityNoticeFrom.value.form.requestStartTime > qualityNoticeFrom.value.form.requestEndTime) {
            message.error('要求开始时间应小于要求结束时间')
            return;
          }
          // 要求开始时间应小于要求结束时间
          if (qualityNoticeFrom.value.form.whetherCausesMachineHalt) {
            if (qualityNoticeFrom.value.form.machineHaltStartTime > qualityNoticeFrom.value.form.machineHaltEndTime) {
              message.error('停机开始时间应小于停机结束时间')
              return;
            }
          }
          data.value = {
            ...data.value,
            ...qualityNoticeFrom.value.form
          }
          active.value++
        } else {
          console.log('error submit!')
          return false
        }
      })
    }
  }
}
// 上一步
const prov = () => {
  if (active.value == 0) return
  active.value--
}
watch(
  () => active.value,
  (val) => {
    if(val == 2){
      // 如果是详情不显示保存
      if(disabled.value){
        Butttondata = [
          defaultButtons.formCloseBtn(null) // 关闭
        ]
      }else{
        Butttondata = [
          defaultButtons.formSaveBtn(null), // 保存
          defaultButtons.formCloseBtn(null) // 关闭
        ]
      }
     
    }else{
      Butttondata = [
        defaultButtons.formCloseBtn(null) // 关闭
      ]
    }
  }
)
</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>