<!--供应商管理-->
<template>
  <div class="vue-element-page-wrap" ref="tableContainer">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form
        ref="queryFormRef"
        :model="state.queryParams.params"
        :inline="true"
        @submit.native.prevent
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="时间范围" prop="params.USERNAME">
              <el-date-picker
                v-model="queryParams.params.DateValue"
                type="datetimerange"
                unlink-panels
                range-separator="To"
                v-model:start-placeholder="queryParams.params.FROMDATE"
                v-model:end-placeholder="queryParams.params.TODATE"
                :shortcuts="shortcuts2"
                :size="size"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="生产订单" prop="WORKORDER">
              <el-Input v-model="queryParams.params.WORKORDER" placeholder="生产订单" clearable />
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="queryInfo">搜索</el-button>
        <el-button type="primary" @click="addFn">新增</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <div class="page-table-title-left">
            <span>生产订单信息列表</span>
          </div>
        </div>
        <div class="page-table-operateBtns">
          <el-popover
            :persistent="false"
            placement="right"
            popper-class="config-table-wrap"
            trigger="click"
          >
            <template #reference>
              <el-button class="operateBtns-setting">
                <svg-icon icon-class="table_title" width="16px" height="16px" />
              </el-button>
            </template>
            <ConfigTable :list="column" @updateList="updateList" />
          </el-popover>
        </div>
      </div>

      <el-table
        border
        :height="tableHeight"
        v-loading="loading"
        :data="state.supplierList"
        highlight-current-row
        row-key="id"
        style="width: 100%"
      >
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <template v-for="(col, index) in column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="col.field === 'status'">
                <span v-if="scope.row[col.field]" class="table-status-active">启用</span>
                <span v-else class="table-status-inActive">禁用</span>
              </span>
              <span v-else>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
        <el-table-column
          width="160"
          label="操作"
          align="center"
          class-name="table-operation"
          fixed="right"
        >
          <template #default="scope">
            <div class="splitLine"></div>
            <el-button type="danger" link @click="handleDel(scope.row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:pageNumTo="queryParams.pageNum"
        v-model:pageSizeTo="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </div>
    <el-dialog
      v-model="dialog.visible"
      title="新增返工/复卷工单维护"
      width="500"
    >
      <el-row :gutter="20" style="margin-top: 10px;">
        <el-col :span="10">
          <el-radio-group v-model="paramsObj.check">
          <el-radio :value="1">单笔维护</el-radio>
          <el-radio :value="2">批量维护</el-radio>
        </el-radio-group>
        </el-col>
        <!-- <el-col :span="6">工单不能重复</el-col> -->
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="10" v-show="paramsObj.check == 1">
          <el-form-item label="" prop="workOrder">
            <el-Input v-model="paramsObj.workOrder" placeholder="生产订单" clearable />
          </el-form-item>
        </el-col>
        <!-- :auto-upload="false" -->
        <el-col :span="10" v-show="paramsObj.check == 2">
          <el-upload
            ref="uploadRef"
            :limit="1"
            action=""
            accept=".xlsx, .xls"
            :on-exceed="exceedFile"
            :on-error="handleError"
            :on-success="handleSuccess"
            :before-upload="beforeUPload"
            :show-file-list="true"
            v-model:file-list="paramsObj.fileList"
            :http-request="uploadRequest"
          >
            <el-button type="primary" style="width: 120px">选择excel文件导入</el-button>
          </el-upload>
        </el-col>
        <el-col :span="4">
          <el-button
            v-show="paramsObj.check == 2"
            style="float: right"
            type="primary"
            text
            @click="downLoadExlce"
            >模板下载</el-button
          >
        </el-col>
        <!-- <el-col :span="4">
          <el-button type="primary" @click="submitForm(paramsObj.check)">保 存</el-button>
        </el-col> -->
      </el-row>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" v-show="paramsObj.check == 1" @click="submitForm(paramsObj.check)">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
export default {
  name: 'WorkOrderMaint'
}
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, toRefs, getCurrentInstance, nextTick } from 'vue'
import { ElForm, ElMessageBox, ElTable, UploadInstance } from 'element-plus'
import { getUserRoleList, updateUserRole } from '@/api/user'
import { getRSAPublic } from '@/api/auth'
import { JSEncrypt } from 'jsencrypt'
import { getQueryList, BpelEvent, getQueryPageList } from '@/api/common'
import { AddWorkOrder, DelWorkOrder, excelWorkOrder } from '@/api/basics/workOrder'
import { bTableHeight } from '../../../../composables/calcTableHeight'
import { msToDate } from '@/utils/CommonUtil'
import axios from 'axios';
import { localStorageTime } from "@/utils/storage";
const { tableContainer, tableHeight, updateTableHeight, handleResize } = bTableHeight(180)
const queryFormRef = ref(ElForm)
const formDataRef = ref(ElForm)
const { proxy }: any = getCurrentInstance()
let statuButton = 0
const roleTableRef = ref<InstanceType<typeof ElTable>>()
const uploadRef = ref<UploadInstance>()

const formDataRefData = ref({
  SUPPLIERNO: '',
  SUPPLIERNAME: '',
  DESCRIPTION: '',
  MATERIALSPECDESCRIPTION: '',
  NATIONALNO: '',
  ADDRESS: '',
  TEL: '',
  FAX: '',
  INCHARGE: '',
  EMAIL: '',
  CITY: ''
})
//formdata时间设置
const size = ref<'default' | 'large' | 'small'>('default')
const state = reactive({
  paramsObj: {
    check: 1,
    workOrder: '',
    fileList: [],
    userId: localStorage.getItem('userId')
  },
  disableds: false,
  loadings: false,
  rsa: '',
  DBProcessType: 'save',
  queryParams: {
    queryId: 'GetWorkOrderList',
    version: 'W10001',
    params: {
      DateValue: '',
      FROMDATE: '',
      TODATE: '',
      WORKORDER:''
    },
    pageNum: 1,
    pageSize: 10
  },
  ChangeParams: {
    header: {
      messageName: '',
      LANGUAGE: 'Chinese'
    },
    body: {
      SUPPLIERNO: '',
      SUPPLIERNAME: '',
      DESCRIPTION: '',
      MATERIALSPECDESCRIPTION: '',
      NATIONALNO: '',
      ADDRESS: '',
      TEL: '',
      FAX: '',
      INCHARGE: '',
      EMAIL: '',
      CITY: '',
      LASTEVENTTIME: ''
    }
  },
  total: 0,
  loading: false,
  supplierList: [] as any,
  dialog: {
    title: '新增用户',
    visible: false
  },

  formData: {
    SUPPLIERNO: '',
    SUPPLIERNAME: '',
    NATIONALNO: '',
    DESCRIPTION: '',
    ADDRESS: '',
    POSTCODE: '',
    CITY: '',
    TEL: '',
    FAX: '',
    EMAIL: '',
    INCHARGE: ''
  } as any,
  rules: {
    account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    pwd: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  },
  column: [] as any,
  selectItem: undefined as any,
  currentTime: '',
  roleDialog: {
    title: '分配角色',
    visible: false
  },
  allRole: [] as any
})
const { paramsObj, queryParams, total, loading, dialog, column, selectItem } = toRefs(state)
//时间范围定义
const shortcuts2 = [
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]
onMounted(() => {
  state.column = [
    { header: '生产订单', field: 'WORKORDER', hide: false },
    { header: '维护人', field: 'CREATENAME', hide: false },
    { header: '维护时间', field: 'CREATETIME', hide: false }
  ]
  // 初始化时调用 handleQuery
  handleQuery()
  updateTableHeight()
  window.addEventListener('resize', handleResize)
})

const shortcuts = [
  {
    text: 'Today',
    value: new Date()
  },
  {
    text: 'Yesterday',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24)
      return date
    }
  },
  {
    text: 'A week ago',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
      return date
    }
  }
]
const queryInfo = () => {
  state.queryParams.pageNum = 1
  handleQuery()
}
// 更新列
function updateList(col: any) {
  state.column = col
}
// 数据导入
function uploadRequest(param: any) {
  console.log(param)
  let userId = state.paramsObj.userId || "";
  const formData = new FormData()
  formData.append('file', param.file);
  formData.append('userId', userId);
  excelWorkOrder(formData,{ "Content-Type": "multipart/form-data" }).then((res: any) => {
    handleQuery()
    ElMessageBox.alert("数据导入成功", '提醒框', {
      confirmButtonText: 'OK'
    })
    console.log('fileList',state.paramsObj.fileList)
    // proxy.$ElMessage.success('数据上传成功')
    
  }).catch((error) => {
    console.log(error)
    ElMessageBox.alert(error.response.data.message, '提醒框', {
      confirmButtonText: 'OK'
    })
  })
}
const beforeUPload = (file: any) => {
  // console.log('file', file)
  const isExcel =
    file.type === 'application/vnd.ms-excel' ||
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isExcel) {
    ElMessageBox({
      title: '温馨提示',
      message: '上传文件只能是 xls / xlsx 格式！',
      type: 'warning'
    })
  }
  return isExcel
}
const downLoadExlce = () => {
  let hrefStr = encodeURI('http://172.22.10.217:8086/工单模板.xlsx')
  window.location.href = hrefStr
}
// 文件数超出提示
const exceedFile = () => {
  ElMessageBox.alert('最多只能上传一个文件！', '提醒框', {
    confirmButtonText: 'OK'
  })
}
// 上传错误提示
const handleError = () => {
  ElMessageBox.alert('导入数据失败，请您重新上传！', '提醒框', {
    confirmButtonText: 'OK'
  })
}
//上传成功提示 不调用
const handleSuccess = (response: any, file: any, fileList: any, rowInfo: any) => {
  console.log(response, file, fileList, rowInfo)
  // ElMessageBox.alert('导入数据成功！', '提醒框', {
  //   confirmButtonText: 'OK'
  // })
}
// 文件上传
const submitForm = async (params: any) => {
    AddWorkOrder(state.paramsObj)
      .then((res: any) => {
        proxy.$ElMessage.success('保存成功')
        handleQuery()
      }).catch((error) => {
        console.log(error)
        ElMessageBox.alert(error.response.data.message, '提醒框', {
          confirmButtonText: 'OK'
        })
      })
}
function addFn() {
  state.dialog.visible = true
}
function handleQuery() {
  state.disableds = true
  state.loadings = true
  state.supplierList = []
  if (state.queryParams.params?.DateValue && state.queryParams.params?.DateValue.length > 0) {
    state.queryParams.params.FROMDATE = msToDate(state.queryParams.params.DateValue[0]).hasTime
    state.queryParams.params.TODATE = msToDate(state.queryParams.params.DateValue[1]).hasTime
  }
  getQueryPageList(state.queryParams)
    .then((res: any) => {
      console.log(res.data)
      if (res.data.list.length == 0) {
        ElMessageBox.alert('查无数据', '提醒框', {
          confirmButtonText: 'OK'
        })
        state.disableds = false
        state.loadings = false
      } else {
        state.supplierList = res.data.list
        state.total = res.data.total
        state.disableds = false
        state.loadings = false
      }
    })
    .catch(() => {})
}
function cancel() {
    if (state.paramsObj.fileList.length > 0) {
      uploadRef.value?.clearFiles()
      state.paramsObj.fileList = []
    }
  state.dialog.visible = false
}
function handleDel(row: any) {
  ElMessageBox.confirm('确认删除此工单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      let params = {
        workOrder: row.WORKORDER
      }
      DelWorkOrder(params)
        .then((res: any) => {
          handleQuery()
        })
        .then(() => proxy.$ElMessage.success('删除成功'))
        .catch(() => {})
    })
    .catch(() => {})
}
</script>

<style scoped lang="scss">
// .el-overlay.userRoleModel {}
</style>
