<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <Search :schema="SelectedSet.allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
  </ContentWrap>

    <!-- 列表头部 -->
    <TableHead
      :HeadButttondata="HeadButttondata"
      @button-base-click="buttonBaseClick"
      :routeName="routeName"
      @updataTableColumns="updataTableColumns"
      @searchFormClick="searchFormClick"
      :allSchemas="SelectedSet.allSchemas"
    />

  <!-- 列表 -->
  <ContentWrap>
    <Table
      :columns="tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      v-model:sort="tableObject.sort"
    >
      <template #code="{row}">
        <el-button type="primary" link @click="openDetail(row, '代码', row.code)">
          <span>{{ row.code }}</span>
        </el-button>
      </template>
      <template #action="{ row }">
        <ButtonBase :Butttondata="butttondata(row)" @button-base-click="buttonTableClick($event,row)" />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BasicForm
    ref="basicFormRef"
    @success="formsSuccess"
    :rules="SelectedSetRules"
    :formAllSchemas="SelectedSet.allSchemas"
    :tableAllSchemas="SelectedProject.allSchemas"
    :tableFormRules="SelectedProjectRules"
    :tableData="tableData"
    :apiUpdate="SelectedSetApi.updateSelectedSet"
    :apiCreate="SelectedSetApi.createSelectedSet"
    @searchTableSuccess="searchTableSuccess"
    :isBusiness="true"
    @onChange="onChange"
    @handleAddTable="handleAddTable"
    @handleDeleteTable="handleDeleteTable"
    @submitForm="submitForm"
    :isSearchTableItem="true"
    @formSelectChange="formSelectChange"
  />

  <!-- 详情 -->
  <DetailQmsCode 
    ref="detailRef" 
    :isBasic="false" 
    :allSchemas="SelectedSet.allSchemas" 
    :detailAllSchemas="SelectedProject.allSchemas" 
    :detailAllSchemasRules="SelectedProjectRules"
    :apiCreate="SelectedProjectApi.createSelectedProject"
    :apiUpdate="SelectedProjectApi.updateSelectedProject"
    :apiPage="SelectedProjectApi.getSelectedProjectPage"
    :apiDelete="SelectedProjectApi.deleteSelectedProject" 
    :detailValidate="detailValidate"
    @searchTableSuccessDetail="searchTableSuccessDetail" 
    :detailButtonIsShowEdit=true
    :detailButtonIsShowAdd=true
    :detailButtonIsShowDelete=true
    @detailOpenForm="detailOpenForm"
    @detailBasicFormOnChange="detailBasiFormOnChange"
     :detailButtonIsShowFilter="false"
  />

  <!-- 导入 -->
  <ImportForm ref="importFormRef" url="/qms/selected-set/import" :importTemplateData="importTemplateData" @success="importSuccess" />
</template>

<script setup lang="ts">
import download from '@/utils/download'
import { SelectedSet,SelectedSetRules } from './selectedSet.data'
import * as SelectedSetApi from '@/api/qms/selectedSet'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import { SelectedProject,SelectedProjectRules } from '../selectedProject/selectedProject.data'
import * as SelectedProjectApi from '@/api/qms/selectedProject'
import * as DictDataApi from '@/api/system/dict/dict.data'  
import component from 'virtual:svg-icons-register'
import * as DictTypeApi from '@/api/system/dict/dict.type'
// import TableHead from '@/components/TableHead/src/TableHead.vue'
// import ImportForm from '@/components/ImportForm/src/ImportForm.vue'
// import Detail from '@/components/Detail/src/Detail.vue'

defineOptions({ name: 'SelectedSet' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const route = useRoute() // 路由信息
const tableData = ref([])
const routeName = ref()
const selectDictType = ref()
const optionsList = ref()
routeName.value = route.name
const tableColumns = ref(SelectedSet.allSchemas.tableColumns)

// 查询页面返回
const searchTableSuccess = (formField, searchField, val, formRef) => {
  nextTick(() => {
    const setV = {}
    setV[formField] = val[0][searchField]
    formRef.setValues(setV)
  })
}

// 字段设置 更新主列表字段
const updataTableColumns = (val) => {
  tableColumns.value = val
}

const { tableObject, tableMethods } = useTable({
  getListApi: SelectedSetApi.getSelectedSetPage // 分页接口
})

// 获得表格的各种操作
const { getList, setSearchParams } = tableMethods

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddBtn({hasPermi:'qms:selected-set:query'}), // 新增
  // defaultButtons.defaultImportBtn({hasPermi:'qms:selected-set:import'}), // 导入
  // defaultButtons.defaultExportBtn({hasPermi:'qms:selected-set:export'}), // 导出
  defaultButtons.defaultFreshBtn(null), // 刷新
  defaultButtons.defaultFilterBtn(null), // 筛选
  defaultButtons.defaultSetBtn(null), // 设置
  // {
  //   label: '自定义扩展按钮',
  //   name: 'zdy',
  //   hide: false,
  //   type: 'primary',
  //   icon: 'Select',
  //   color: ''
  // },
]

// 头部按钮事件
const buttonBaseClick = (val, item) => {
  if (val == 'add') { // 新增
    openForm('create')
  } else if (val == 'import') { // 导入
    handleImport()
  } else if (val == 'export') { // 导出
    handleExport()
  } else if (val == 'refresh') { // 刷新
    getList()
  } else if (val == 'filtrate') { // 筛选
  } else { // 其他按钮
    console.log('其他按钮', item)
  }
}

const isShowMainButton = (row,val) => {
  if (val.indexOf(row.available) > -1) {
    return false
  } else {
    return true
  }
}

const butttondata = (row) => {
  return [
    defaultButtons.mainListEditBtn({hasPermi: 'qms:selected-set:update'}),
    defaultButtons.mainListEnableBtn({hide:isShowMainButton(row,['FALSE']),hasPermi:'qms:selected-set:enable'}),
    defaultButtons.mainListDisableBtn({hide:isShowMainButton(row,['TRUE']),hasPermi:'qms:selected-set:disable'}),
  ]
}

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'edit') { // 编辑
    editForm('update', row)
  } else if (val == 'delete') { // 删除
    handleDelete(row.id)
  }else if (val == 'enable') {
    handleEnable(row.id)
  }else if (val == 'disable') {
    handleDisable(row.id)
  }
}

/** 添加/修改操作 */
const basicFormRef = ref()
const openForm = (type: string, row?: any) => {
  tableData.value = []
  basicFormRef.value.open(type, row)
}
const editForm = async (type: string, row?: any) => {
  tableData.value = []
  SelectedProjectApi.getSelectedProjectNoPage({masterId:row.id}).then(res=>{
    tableData.value = res
  })
  basicFormRef.value.open(type, row)
}

// form表单提交
const formsSuccess = async (formType,data) => {
  var isHave =SelectedSet.allSchemas.formSchema.some(function (item) {
    return item.field === 'activeTime' || item.field === 'expireTime';
  });
  if(isHave){
    if(data.activeTime && data.expireTime && data.activeTime >=data.expireTime){
      message.error('失效时间要大于生效时间')
      return;
    }
  }
  if(data.activeTime==0)data.activeTime = null;
  if(data.expireTime==0)data.expireTime = null;
  if (formType === 'create') {
    await SelectedSetApi.createSelectedSet(data)
    message.success(t('common.createSuccess'))
  } else {
    await SelectedSetApi.updateSelectedSet(data)
    message.success(t('common.updateSuccess'))
  }
  basicFormRef.value.dialogVisible = false
  getList()
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (row: any, titleName: any, titleValue: any) => {
  selectDictType.value = row.classification
  detailRef.value.openDetail(row, titleName, titleValue, 'basicSelectedSet')
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SelectedSetApi.deleteSelectedSet(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
const handleEnable = async (id: number) => {
  try {
    await SelectedSetApi.enableSelectedSet(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
const handleDisable = async (id: number) => {
  try {
    await SelectedSetApi.disableSelectedSet(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
/** 导出按钮操作 */
const exportLoading = ref(false) // 导出的加载中
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await SelectedSetApi.exportSelectedSet(tableObject.params)
    download.excel(data, '选定集.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}
// 导入附件弹窗所需的参数
const importTemplateData = reactive({
  templateUrl: '',
  templateTitle: '选定集导入模版.xlsx'
})
// 导入成功之后
const importSuccess = () => {
  getList()
}

// 筛选提交
const searchFormClick = (searchData) => {
  tableObject.params = {
    isSearch: true,
    filters: searchData.filters
  }
  getList() // 刷新当前列表
}


const tableFormKeys = {}
SelectedProject.allSchemas.tableFormColumns.forEach((item) => {
  tableFormKeys[item.field] = item.default ? item.default : ''
})

// 添加明细
const handleAddTable = () => {
  tableData.value.push(JSON.parse(JSON.stringify(tableFormKeys)))
}
// 删除明细
const handleDeleteTable = (item, index) => {
  tableData.value.splice(index, 1)
}


// 主子数据 提交
const submitForm = async (formType, data) => {
  const emptyFlag = validateDetailEmpty(tableData.value);
  if(!emptyFlag){
    message.alertWarning('明细不能为空')
    basicFormRef.value.formLoading = false
    return
  }
  if(!validateNotRepetition(tableData.value)){
    message.alertWarning('选定集字典及字典项不能重复')
    basicFormRef.value.formLoading = false
    return
  }
  data.selectedProjectDOList = tableData.value// 拼接子表数据参数
  data.selectedProjectDOList = data.selectedProjectDOList.map(item => {
    // 按照 '-%%%-'' 拆分 dictionaryCode
    const [dictionaryCode, dictionaryValue] = item.dictionaryTypeAndCode.split('-%%%-');
    const dictionary = optionsList.value.find(temp => temp.options.some(option => option.value === item.dictionaryTypeAndCode))
    const dictionaryLabel = dictionary?.options.find(option => option.value === item.dictionaryTypeAndCode)?.label
    // 返回一个新对象，包含拆分后的 dictionaryCode 和 dictionaryValue，以及原始项中的其他属性
    return {
      ...item,
      dictionaryCode,
      dictionaryValue,
      dictionaryLabel
    };
  });
  try {
    if (formType === 'create') {
      await SelectedSetApi.createSelectedSet(data)
      message.success(t('common.createSuccess'))
    } else {
      await SelectedSetApi.updateSelectedSet(data)
      message.success(t('common.updateSuccess'))
    }
    basicFormRef.value.dialogVisible = false
    // 刷新当前列表
    getList()
  } finally {
    basicFormRef.value.formLoading = false
  }
}
const validateDetailEmpty = (data) => {
  const codes = data.map(item => item.stage);
  if(codes.length == 0){
    return false;
  }
  return true;
}
const updateSelections = async (masterId,row) => {
  let param = { masterId: masterId };
  SelectedProjectApi.getSelectedProjectNoPage(param).then(res => {
    DictTypeApi.getDictTypeAndData('inspection').then(originalResponse => {
      // 首先对每个element进行映射和过滤
      const response = originalResponse.map(element => {
        const options = element.dictDataRespVOList.map(item => {
          return {
            value: element.type + "-%%%-" + item.value,
            label: element.name + "-" + item.label
          };
        }).filter(option => {
          // 过滤掉与res中任何dictionaryTypeAndCode相等的option
          return !res.some(resItem => {
            if(row != null){
              return option.value === resItem.dictionaryTypeAndCode && option.value != row.dictionaryTypeAndCode
            }else{
              return option.value === resItem.dictionaryTypeAndCode
            }
            
          });
        });
        return { ...element, options }; // 返回新的element，包含过滤后的options
      }).filter(element => element.options.length > 0); // 再次过滤，移除options为空的element

      // 更新对应字段的options
      const formSchemaItem = SelectedProject.allSchemas.formSchema.find(item => item.field === 'dictionaryTypeAndCode');
      if (formSchemaItem) {
        formSchemaItem.componentProps.options = response;
      }
    });
  });
};

const validateNotRepetition = (data) => {
  // 提取所有的 dictionaryTypeAndCode 值
  const codes = data.map(item => item.dictionaryTypeAndCode);
  
  // 创建一个 Set 来存储唯一的 dictionaryTypeAndCode 值
  const uniqueCodes = new Set(codes);
  
  // 如果原始数组的长度大于 Set 集合的大小，则说明有重复
  if (codes.length > uniqueCodes.size) {
    return false; // 发现重复，返回 false
  }
  
  return true; // 未发现重复，返回 true
};


const detailValidate = (data) => {
  let tag = true;
  return tag
}

const detailOpenForm = (type, row, masterParmas) => {
  if(type == 'create'){
    updateSelections(masterParmas.masterId,row)
  }else if('update'){
    updateSelections(masterParmas.masterId,row)
  }
  
}



const detailBasiFormOnChange = (field,val,detailFormRef) => {
  if(field == 'dictionaryTypeAndCode'){
    // 按照 '-%%%-'' 拆分 dictionaryCode
    const [dictionaryCode, dictionaryValue] = val.split('-%%%-');
    const dictionary = optionsList.value.find(temp => temp.options.some(option => option.value === val))
    const dictionaryLabel = dictionary?.options.find(option => option.value === val)?.label  
    const setV = {}
    setV['dictionaryLabel'] = dictionaryLabel
    setV['dictionaryCode'] = dictionaryCode
    setV['dictionaryValue'] = dictionaryValue
    nextTick(() => {
      detailFormRef.setValues(setV)
    })
  }
}

const formSelectChange = (a,b,c,d) => {
}

const getDicDetails = ()=>{
  DictTypeApi.getDictTypeAndData('inspection').then(res=>{
    res.forEach(element => {
      element.options = element.dictDataRespVOList.map(item => {
        return {
          value: element.type + "-%%%-" + item.value,
          label: element.name + "-" + item.label
        }
      })
    })
    optionsList.value = res
  })
}

/** 初始化 **/
onMounted(async () => {
  getList()
  getDicDetails()
  importTemplateData.templateUrl = await SelectedSetApi.importTemplate()
})

</script>
