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

    <!-- 列表头部 -->
    <TableHead
      :HeadButttondata="HeadButttondata"
      @button-base-click="buttonBaseClick"
      :routeName="routeName"
      @updataTableColumns="updataTableColumns"
      @searchFormClick="searchFormClick"
      :allSchemas="Monomer.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,$index }">
        <ButtonBase :Butttondata="butttondata(row,$index)" @button-base-click="buttonTableClick($event,row)" />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BasicForm
    ref="basicFormRef"
    @success="formsSuccess"
    :rules="MonomerRules"
    :formAllSchemas="Monomer.allSchemas"
    :apiUpdate="MonomerApi.updateMonomer"
    :apiCreate="MonomerApi.createMonomer"
    @searchTableSuccess="searchTableSuccess"
    :isBusiness="false"
  >
    <template #tableForm>
      <!-- 单体产线设备 -->
      <div class="table">
        <TableForm
          ref="tableFormDeviceRef"
          class="w-[100%]"
          :isShowButton="isStatic&&tableDataDevice.length==0||!isStatic"
          :isShowReduceButtonSelection="true"
          :tableFields="CellDevice.allSchemas.tableFormColumns"
          :tableData="tableDataDevice"
          :tableFormRules="CellDeviceRules"
          @handleAddTable="handleAddTable('Device')"
          @handleDeleteTable="(item, index)=>handleDeleteTable(item, index,'Device')"
          @tableSelectionDelete="(selection)=>tableSelectionDelete(selection,'Device')"
          @inpuFocus="inpuFocus"
          @inputStringBlur="inputStringBlur"
          :routeName="routeName"
        >
          <!-- <template v-slot="{ row }">
            <slot :row="row"></slot>
          </template> -->
        </TableForm>
      </div>
      <!-- 单体产线环境 -->
      <div class="table marr20">
        <TableForm
          ref="tableFormEnvRef"
          class="w-[100%]"
          :isShowButton="isStatic&&tableDataEnv.length==0||!isStatic"
          :isShowReduceButtonSelection="true"
          :tableFields="CellEnv.allSchemas.tableFormColumns"
          :tableData="tableDataEnv"
          :tableFormRules="CellEnvRules"
          @handleAddTable="handleAddTable('Env')"
          @handleDeleteTable="(item, index)=>handleDeleteTable(item, index,'Env')"
          @tableSelectionDelete="(selection)=>tableSelectionDelete(selection,'Env')"
          @inpuFocus="inpuFocus"
          @inputStringBlur="inputStringBlur"
          :routeName="routeName"
        >
          <!-- <template v-slot="{ row }">
            <slot :row="row"></slot>
          </template> -->
        </TableForm>
      </div>
      <!-- 单体极片 -->
      <div class="table marr20">
        <TableForm
          ref="tableFormPlateRef"
          class="w-[100%]"
          :isShowButton="isStatic&&tableDataPlate.length==0||!isStatic"
          :isShowReduceButtonSelection="true"
          :tableFields="CellPlate.allSchemas.tableFormColumns"
          :tableData="tableDataPlate"
          :tableFormRules="CellPlateRules"
          @handleAddTable="handleAddTable('Plate')"
          @handleDeleteTable="(item, index)=>handleDeleteTable(item, index,'Plate')"
          @tableSelectionDelete="(selection)=>tableSelectionDelete(selection,'Plate')"
          @inpuFocus="inpuFocus"
          @inputStringBlur="inputStringBlur"
          :routeName="routeName"
        >
          <!-- <template v-slot="{ row }">
            <slot :row="row"></slot>
          </template> -->
        </TableForm>
      </div>
      <!-- 单体卷芯或叠芯 -->
      <div class="table marr20">
        <TableForm
          ref="tableFormCoreRef"
          class="w-[100%]"
          :isShowButton="isStatic&&tableDataCore.length==0||!isStatic"
          :isShowReduceButtonSelection="true"
          :tableFields="CellCore.allSchemas.tableFormColumns"
          :tableData="tableDataCore"
          :tableFormRules="CellCoreRules"
          @handleAddTable="handleAddTable('Core')"
          @handleDeleteTable="(item, index)=>handleDeleteTable(item, index,'Core')"
          @tableSelectionDelete="(selection)=>tableSelectionDelete(selection,'Core')"
          @inpuFocus="inpuFocus"
          @inputStringBlur="inputStringBlur"
          :routeName="routeName"
        >
          <!-- <template v-slot="{ row }">
            <slot :row="row"></slot>
          </template> -->
        </TableForm>
      </div>
      <!-- 单体产品 -->
      <div class="table marr20">
        <TableForm
          ref="tableFormProdRef"
          class="w-[100%]"
          :isShowButton="isStatic&&tableDataProd.length==0||!isStatic"
          :isShowReduceButtonSelection="true"
          :tableFields="CellProd.allSchemas.tableFormColumns"
          :tableData="tableDataProd"
          :tableFormRules="CellProdRules"
          @handleAddTable="handleAddTable('Prod')"
          @handleDeleteTable="(item, index)=>handleDeleteTable(item, index,'Prod')"
          @tableSelectionDelete="(selection)=>tableSelectionDelete(selection,'Prod')"
          @inpuFocus="inpuFocus"
          @inputStringBlur="inputStringBlur"
          :routeName="routeName"
        >
          <!-- <template v-slot="{ row }">
            <slot :row="row"></slot>
          </template> -->
        </TableForm>
      </div>
      <!-- 单体产品 -->
      <div class="table marr20">
        <TableForm
          ref="tableFormPassRef"
          class="w-[100%]"
          :isShowButton="isStatic&&tableDataPass.length==0||!isStatic"
          :isShowReduceButtonSelection="true"
          :tableFields="CellPass.allSchemas.tableFormColumns"
          :tableData="tableDataPass"
          :tableFormRules="CellPassRules"
          @handleAddTable="handleAddTable('Pass')"
          @handleDeleteTable="(item, index)=>handleDeleteTable(item, index,'Pass')"
          @tableSelectionDelete="(selection)=>tableSelectionDelete(selection,'Pass')"
          @inpuFocus="inpuFocus"
          @inputStringBlur="inputStringBlur"
          :routeName="routeName"
        >
          <!-- <template v-slot="{ row }">
            <slot :row="row"></slot>
          </template> -->
        </TableForm>
      </div>
    </template>
  </BasicForm>
  <SearchTable
    ref="searchTableRef"
    @searchTableSuccess="searchTableSuccess1"/>


  <!-- 详情 -->
  <Detail ref="detailRef" :isBasic="true" :allSchemas="Monomer.allSchemas" />

  <!-- 导入 -->
  <ImportForm ref="importFormRef" url="/battery/cell-device/import" :importTemplateData="importTemplateData" @success="importSuccess" />
</template>

<script setup lang="ts">
// 单体产线设备
import * as CellDeviceApi from '@/api/battery/cellDevice'
import { CellDevice,CellDeviceRules } from '@/views/battery/cellDevice/cellDevice.data'
// 单体产线环境
import * as CellEnvApi from '@/api/battery/cellEnv'
import { CellEnv,CellEnvRules } from '@/views/battery/cellEnv/cellEnv.data'
// 单体极片
import { CellPlate,CellPlateRules } from '@/views/battery/cellPlate/cellPlate.data'
import * as CellPlateApi from '@/api/battery/cellPlate'
// 单体卷芯或叠芯
import { CellCore,CellCoreRules } from '@/views/battery/cellCore/cellCore.data'
import * as CellCoreApi from '@/api/battery/cellCore'
// 单体产品
import { CellProd,CellProdRules } from '@/views/battery/cellProd/cellProd.data'
import * as CellProdApi from '@/api/battery/cellProd'
// 单体直通率
import { CellPass,CellPassRules } from '@/views/battery/cellPass/cellPass.data'
import * as CellPassApi from '@/api/battery/cellPass'


import download from '@/utils/download'
import { Monomer,MonomerRules } from './monomer.data'
import * as MonomerApi from '@/api/battery/monomer'
import * as defaultButtons from '@/utils/disposition/defaultButtons'
import TableHead from '@/components/TableHead/src/TableHead.vue'
import ImportForm from '@/components/ImportForm/src/ImportForm.vue'
import Detail from '@/components/Detail/src/Detail.vue'
import {defaultAddStaticBtn} from "@/utils/disposition/defaultButtons";

defineOptions({ name: 'CellDevice' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const tableColumns = ref(Monomer.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: MonomerApi.getMonomerPage // 分页接口
})

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

// 列表头部按钮
const HeadButttondata = [
  defaultButtons.defaultAddStaticBtn({hasPermi:'battery:monomer:update'}), // 静态数据
  defaultButtons.defaultAddBtn({hasPermi:'battery:monomer:create'}), // 新增
  // defaultButtons.defaultImportBtn({hasPermi:'battery:cellDevice:import'}), // 导入
  defaultButtons.defaultExportBtn({hasPermi:'battery:monomer: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 == 'addStatic'||val == 'addDynamic') { // 新增
    isStatic.value = val == 'addStatic'
    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 butttondata = (row,$index) => {

  return [
    defaultButtons.mainListEditBtn({hasPermi:'battery:monomer:update'}), // 编辑
    defaultButtons.mainListReleaseBtn({hide:(row.release =='0' || row.type !='static'),hasPermi:'battery:monomer:update'}), // 发布
    defaultButtons.mainListDeleteBtn({hide:row.type =='static' ,hasPermi:'battery:monomer:delete'}), // 删除
  ]
}

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

/** 添加/修改操作 */
const basicFormRef = ref()
const openForm = (type: string, row?: any) => {
  if(tableObject.tableList.length>0){
    if(isStatic.value){
      // 静态
      row = tableObject.tableList.find(item=>item.type == 'static')
    }else{
      // 动态
      row = tableObject.tableList.find(item=>item.type == 'moving')
    }
  }
  basicFormRef.value.open(type, row)
}

// form表单提交
const formsSuccess = async (formType,data) => {
  var isHave =Monomer.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 MonomerApi.createMonomer(data)
    message.success(t('common.createSuccess'))
  } else {
    await MonomerApi.updateMonomer(data)
    message.success(t('common.updateSuccess'))
  }
  basicFormRef.value.dialogVisible = false
  getList()
}

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

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MonomerApi.deleteMonomer(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 MonomerApi.exportMonomer(tableObject.params)
    download.excel(data, 'battery_cell_device.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

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

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


const tableFormDeviceRef = ref()
const tableDataDevice = ref([]) //单体产线设备

const tableFormEnvRef = ref()
const tableDataEnv = ref([]) //单体产线环境

const tableFormPlateRef = ref()
const tableDataPlate = ref([]) //单体极片


const tableFormCoreRef = ref()
const tableDataCore = ref([]) //单体卷芯或叠芯

const tableFormProdRef = ref()
const tableDataProd = ref([]) //单体产品

const tableFormPassRef = ref()
const tableDataPass = ref([]) //单体直通率


// 添加明细表单
const searchTableRef = ref()
const isStatic = ref(true)

// 'Device' 'Env'
const addTableType = ref('')
const handleAddTable = (type)=>{
  addTableType.value = type
  let allSchemas = CellDevice.allSchemas
  let apiPage = CellDeviceApi.getCellDevicePage
  let tableTitle = ''
  if(type == 'Device'){
    // 设备
    tableTitle = '单体产线设备'
    allSchemas = CellDevice.allSchemas
    apiPage = CellDeviceApi.getCellDevicePage
  }else if(type == 'Env'){
    // 环境
    tableTitle = '单体产线环境'
    allSchemas = CellEnv.allSchemas
    apiPage = CellEnvApi.getCellEnvPage
  }else if(type == 'Plate'){
    // 单体极片
    tableTitle = '单体极片'
    allSchemas = CellPlate.allSchemas
    apiPage = CellPlateApi.getCellPlatePage
  }else if(type == 'Core'){
    // 单体卷芯或叠芯
    tableTitle = '单体卷芯或叠芯'
    allSchemas = CellCore.allSchemas
    apiPage = CellCoreApi.getCellCorePage
  }else if(type == 'Prod'){
    // 单体产品
    tableTitle = '单体产品'
    allSchemas = CellProd.allSchemas
    apiPage = CellProdApi.getCellProdPage
  }else if(type == 'Pass'){
    // 单体直通率
    tableTitle = '单体直通率'
    allSchemas = CellPass.allSchemas
    apiPage = CellPassApi.getCellPassPage
  }


  searchTableRef.value.open(
    tableTitle,
    allSchemas,
    apiPage,
    "hahaha",
    "hahaha",
    !isStatic.value,
    'tableForm',
    null,
    {
      // 参数
      // supplierCode:formRef.value.formRef.formModel.supplierCode,
      // itemCode:formRef.value.formRef.formModel.itemCode
    },
    undefined,
    false,
    undefined
  )
}
 // 删除明细
const handleDeleteTable = (item, index, type) => {
    if(type == 'Device'){
    // 设备
    tableDataDevice.value.splice(index, 1)
  }else if(type == 'Env'){
    // 环境
    tableDataEnv.value.splice(index, 1)
  }else if(type == 'Plate'){
    // 单体极片
    tableDataPlate.value.splice(index, 1)
  }else if(type == 'Core'){
    // 单体卷芯或叠芯
    tableDataCore.value.splice(index, 1)
  }else if(type == 'Prod'){
    // 单体产品
    tableDataProd.value.splice(index, 1)
  }else if(type == 'Pass'){
    // 单体直通率
    tableDataPass.value.splice(index, 1)
  }
}
// 批量删除
const tableSelectionDelete = (selection,type) => {
  if(type == 'Device'){
    // 设备
    tableDataDevice.value = tableDataDevice.value.filter(item => !selection.includes(item))
  }else if(type == 'Env'){
    // 环境
    tableDataEnv.value = tableDataEnv.value.filter(item => !selection.includes(item))
  }else if(type == 'Plate'){
    // 单体极片
    tableDataPlate.value = tableDataPlate.value.filter(item => !selection.includes(item))
  }else if(type == 'Core'){
    // 单体卷芯或叠芯
    tableDataCore.value = tableDataCore.value.filter(item => !selection.includes(item))
  }else if(type == 'Prod'){
    // 单体产品
    tableDataProd.value = tableDataProd.value.filter(item => !selection.includes(item))
  }else if(type == 'Pass'){
    // 单体直通率
    tableDataPass.value = tableDataPass.value.filter(item => !selection.includes(item))
  }
}
// 弹层确定返回所选数据
// val ： 弹层列表row 数据
const searchTableSuccess1 = (formField, searchField, val, type, row) => {
  console.log('searchTableSuccess1',formField, searchField, val, type, row)
  if (formField == 'hahaha') {
    if(addTableType.value == 'Device'){
      // 设备
      tableDataDevice.value = tableDataDevice.value.concat(val)
    }else if(addTableType.value == 'Env'){
      // 环境
      tableDataEnv.value = tableDataEnv.value.concat(val)
    }else if(addTableType.value == 'Plate'){
      // 单体极片
      tableDataPlate.value = tableDataPlate.value.concat(val)
    }else if(addTableType.value == 'Core'){
      // 单体卷芯或叠芯
      tableDataCore.value = tableDataCore.value.concat(val)
    }else if(addTableType.value == 'Prod'){
      // 单体产品
      tableDataProd.value = tableDataProd.value.concat(val)
    }else if(addTableType.value == 'Pass'){
      // 单体直通率
      tableDataPass.value = tableDataPass.value.concat(val)
    }
  }
}
const inpuFocus = ()=>{
  
}
const inputStringBlur = ()=>{
  
}

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

</script>

<style lang="scss" scoped>
.marr20{
  margin-top: 20px;
}
.table {
  border: 1px solid #dedede;
  border-radius: 8px;
  padding: 10px;
  width: calc(100% - 32px);
  display: flex;
  ::v-deep(.el-table__body) {
    padding: 10px 0px;
  }
  ::v-deep(.el-table--default .el-table__cell) {
    padding: 2px 0px;
    border: none;
  }

  ::v-deep(.el-table td.el-table__cell .el-form-item__content) {
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
  }
  ::v-deep(.el-table td.el-table__cell div) {
    overflow: visible;
  }

  ::v-deep(.el-icon) {
    display: block;
  }
}
button .button {
  > div {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    > div {
      margin-left: 6px;
      text-decoration: underline;
      color: #409eff;
    }
  }
}
</style>
