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

    <!-- 列表头部 -->
    <TableHead
      :HeadButttondata="HeadButttondata"
      @button-base-click="buttonBaseClick"
      :routeName="routeName"
      @updataTableColumns="updataTableColumns"
      @searchFormClick="searchFormClick"
      :allSchemas="EquipmentReportRepairRequest.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 #number="{row}">
        <el-button type="primary" link @click="openDetail(row, '代码', row.number)">
          <span>{{ row.number }}</span>
        </el-button>
      </template>
      <template #action="{ row }">
        <ButtonBase :Butttondata="butttondata(row)" @button-base-click="buttonTableClick($event,row)" />
      </template>
      <template #images="{ row }">
        <ButtonBase v-if="row.images === 'TRUE' ":Butttondata="butttondataView(row)" @button-base-click="buttonTableClick($event, row)" />
      </template>
    </Table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BasicForm
    ref="basicFormRef"
    @success="formsSuccess"
    :rules="EquipmentReportRepairRequestRules"
    :formAllSchemas="EquipmentReportRepairRequest.allSchemas"
    :apiUpdate="EquipmentReportRepairRequestApi.updateEquipmentReportRepairRequest"
    :apiCreate="EquipmentReportRepairRequestApi.createEquipmentReportRepairRequest"
    @searchTableSuccess="searchTableSuccess"
    :isBusiness="false"
    @onChange="onChange"
  />

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

  <Dialog
    ref="basicFormViewRef"
    v-model="showView"
    :key="viewKey"
    :closeOnClickModal="true"
    :title="viewTitle"
  >
    <el-image v-for="url in urls" :key="url" :src="url" lazy />
  </Dialog>

  <!-- 审核页面 -->
  <AudiForm ref="audiFormRef" @success="getData" @close="getClosed"/>

  <!-- 导入 -->
  <ImportForm ref="importFormRef" url="/eam/equipment-report-repair-request/import" :importTemplateData="importTemplateData" @success="importSuccess" />
</template>


<script setup lang="ts">
import download from '@/utils/download'
import { EquipmentReportRepairRequest,EquipmentReportRepairRequestRules } from './equipmentReportRepairRequest.data'
import * as EquipmentReportRepairRequestApi from '@/api/eam/equipmentReportRepairRequest'
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 AudiForm from '@/views/eam/equipmentReportRepairRequest/audiForm.vue'
import {EquipmentAccounts} from "@/views/eam/equipmentAccounts/equipmentAccounts.data";
import * as EquipmentItemApi from "@/api/eam/equipmentAccounts";
import {ToolAccounts} from "@/views/eam/toolAccounts/toolAccounts.data";
import * as ToolItemApi from "@/api/eam/toolAccounts";
import * as EquipmentReportRepairApi from "@/api/eam/equipmentReportRepairRequest";

defineOptions({ name: 'EquipmentReportRepairRequest' })

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

const route = useRoute() // 路由信息
const routeName = ref()
routeName.value = route.name
const showView = ref(false)
const urls = ref([])
const viewKey = ref(0)
const viewTitle = ref('图片预览')
const tableColumns = ref(EquipmentReportRepairRequest.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: EquipmentReportRepairRequestApi.getEquipmentReportRepairRequestPage // 分页接口
})

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

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

// 列表-操作按钮
const butttondataView = (row) => {
  return [
    defaultButtons.viewBtn(null),
  ]
}

// 头部按钮事件
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 isShowStatusButton = (row,val) => {
  if (val.indexOf(row.status) > -1) {
    return false
  } else {
    return true
  }
}

// 列表-操作按钮
const butttondata = (row) => {
  return [
    //defaultButtons.mainListEditBtn({hide: isShowStatusButton(row, ['0']),hasPermi: 'eam:equipmentReportRepairRequest:update'}), // 编辑
    defaultButtons.mainListAuditingBtn({hide: isShowStatusButton(row, ['0']), hasPermi: 'eam:equipmentReportRepairRequest:update'}), // 审核
    defaultButtons.mainListAuditedBtn({hide: isShowStatusButton(row, ['2']), hasPermi: 'eam:equipmentReportRepairRequest:update'}), // 审核完成
    defaultButtons.mainListRevokeBtn({hide: isShowStatusButton(row, ['0']), hasPermi: 'eam:equipmentReportRepairRequest:update'}), // 撤回
    defaultButtons.mainListFinishBtn({hide: isShowStatusButton(row,['3']),hasPermi:'eam:equipmentReportRepairRequest:update'}),
    defaultButtons.mainListDeleteBtn({hasPermi:'eam:equipmentReportRepairRequest:update'}), // 删除
  ]
}

// 列表-操作按钮事件
const buttonTableClick = async (val, row) => {
  if (val == 'edit') { // 编辑
    openForm('update', row)
  } else if (val == 'delete') { // 删除
    handleDelete(row.id)
  } else if (val == 'auditing') { // 审核
    handleAuditing(row.id)
  } else if (val == 'revoke') { // 撤回
    handleRevoke(row.id)
  } else if (val == 'audited') { // 审核完成
    handleAudited(row)
  } else if (val == 'finish') { // 完成
    handleFinish(row.id)
  } else if (val == 'view') { //预览
    openForm('view', row)
  }
}

/** 添加/修改操作 */
const basicFormRef = ref()
//图片展示
const basicFormViewRef = ref()
const openForm = async (type: string, row?: any) => {
  if (type == "create") {
    EquipmentReportRepairRequest.allSchemas.formSchema.forEach((item) => {
      if (item.field == 'status') {
      }
    })
  } else {
    EquipmentReportRepairRequest.allSchemas.formSchema.forEach((item) => {
      if (item.field == 'status') {
      }
    })
  }
  if (type == 'view') {
    const formData = ref({
      number: row.number,
      funcCode: 'equipment_report',
      fileBusiType: 'EAM',
    })
    urls.value = []
    let newVar = await EquipmentReportRepairApi.getEquipmentReportFileInfo(formData.value);
    newVar.forEach((item: any) => {
      urls.value.push(item.url);
    })
    showView.value = true
    viewKey.value += 1
  } else {
    basicFormRef.value.open(type, row)
  }
}

// form表单提交
const formsSuccess = async (formType,data) => {
  var isHave =EquipmentReportRepairRequest.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;
  const tags=ref([])
  if (data.images != null && data.images != "") {
    data.images.forEach((item: any) => {
      const newItem = {};
      newItem['name'] = item.name;
      newItem['size'] = item.size;
      newItem['uid'] = item.uid;
      newItem['url'] = item.url;
      tags.value.push(newItem);
    })
  }
  data.fileInfoList = tags.value
  if (formType === 'create') {
    await EquipmentReportRepairRequestApi.createEquipmentReportRepairRequest(data)
    message.success(t('common.createSuccess'))
  } else {
    await EquipmentReportRepairRequestApi.updateEquipmentReportRepairRequest(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, 'basicEquipmentReportRepairRequest')
}

//完成按钮  并生成维修工单
const handleFinish = async (id: number) => {
  await message.delConfirm('是否完成,并创建维修工单？');
  try {
    const params = ref({
      id: '',
      status:'',
    })
    params.value.id = id
    params.value.status = '5'
    await EquipmentReportRepairRequestApi.createEquipmentWeixiuOrder(params.value)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

//审核完成按钮
const handleAudited = async (row) => {
  message.confirmAudi(t('')).then(async () => {
    //打开提交表单
    audiFormRef.value.open('update', row);
  }).catch(async (action: Action) => {
    if(action === 'cancel'){
      const params = ref({
        id: '',
        status:'',
      })
      params.value.id = row.id
      params.value.status = '4'
      await EquipmentReportRepairRequestApi.updateEquipmentReportRepairOrder(params.value)
      message.success(t('common.updateSuccess'))
      // 刷新列表
      await getList()
    }
  })
}

//审核按钮
const audiFormRef = ref()
const handleAuditing = async (id: number) => {
  await message.delConfirm('是否审核所选中工单？');
  try {
    const params = ref({
      id: '',
      status:'',
    })
    params.value.id = id
    params.value.status = '2'
    await EquipmentReportRepairRequestApi.updateEquipmentReportRepairOrder(params.value)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 撤回按钮操作 */
const handleRevoke = async (id: number) => {
  await message.delConfirm('是否撤回所选中工单？');
  try {
    const params = ref({
      id: '',
      status:'',
    })
    params.value.id = id
    params.value.status = '1'
    await EquipmentReportRepairRequestApi.updateEquipmentReportRepairOrder(params.value)
    message.success(t('common.updateSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EquipmentReportRepairRequestApi.deleteEquipmentReportRepairRequest(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 EquipmentReportRepairRequestApi.exportEquipmentReportRepairRequest(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()
}

//audiForm 关闭按钮回传
const getClosed=(val)=> {
  nextTick?.(() => {
    getList()
  })
}

//audiForm 提交按钮回传
const getData=(val)=> {
  nextTick?.(async () => {

      try {
        const params = ref({
          id: '',
          status:'',
        })
        params.value.id = val
        params.value.status = '3'
        await EquipmentReportRepairRequestApi.updateEquipmentReportRepairOrder(params.value)
        message.success(t('工单已流转'))
        // 刷新列表
        await getList()
      } catch {}

    }
  )
}


const onChange = (field, item) => {
  //设备
  if(field == 'type' && item == 'DEVICE'){
    EquipmentReportRepairRequest.allSchemas.formSchema.forEach((items) => {
      if (items.field == 'equipmentCode') {
        basicFormRef.value.formRef.setValues({
          equipmentCode:''
        })
        items.componentProps.searchAllSchemas = EquipmentAccounts.allSchemas
        items.componentProps.searchPage = EquipmentItemApi.getEquipmentAccountsPage
      }
    })
  }
  //工装
  if(field == 'type' && item == 'EQUIPMENT'){
    EquipmentReportRepairRequest.allSchemas.formSchema.forEach((items) => {
      if (items.field == 'equipmentCode') {
        basicFormRef.value.formRef.setValues({
          equipmentCode:''
        })
        items.componentProps.searchAllSchemas = ToolAccounts.allSchemas
        items.componentProps.searchPage = ToolItemApi.getToolAccountsPage
      }
    })
  }
  //图片上传
  if(field == 'images'){
    EquipmentReportRepairRequest.allSchemas.formSchema.forEach((items) => {
      if (items.field == 'images') {
        console.log(items.value);
      }
    })
  }
}

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

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

</script>
