<script lang="ts" setup name="maintenanceAdd">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus'
import type { IOptions } from '../standard_interface'
import { getStaffList } from '@/api/measure/person'
import { getTypeSelect } from '@/api/system/price'
import { getStandardListDetail, getUsersDept } from '@/api/device/standard'
import { UploadFile } from '@/api/measure/file'
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const buttonArray = ref<string[]>([])
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  add: '新建',
  edit: '编辑',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
const $route = useRoute()
console.log($route.meta.title)
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if (pageType.value === 'detail') {
    buttonArray.value = ['同意', '驳回', '拒绝']
  }
  else if (pageType.value === 'edit') {
    buttonArray.value = ['提交']
  }
  else {
    buttonArray.value = ['提交']
  }
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const ruleFormRef = ref<FormInstance>()
// 逻辑代码
const formInline = ref({
  assessDate: '',
  assessmentUnit: '',
  category: null,
  categoryName: '',
  constructionStandardProject: '',
  constructionStandardUnitName: '',
  contactInfo: '',
  createTime: null,
})
// 数据
const list = ref<object[]>([
  { name: '王五' },
])
// 审批弹窗开关
const applyShow = ref(false)
// 审批弹窗信息收集类型
interface applyListType {
  select: string
  epilog: string
  approval: string
  approvalTime: string
}
// 审批弹窗信息收集
const applyList = ref<applyListType>({
  select: '',
  epilog: '',
  approval: '',
  approvalTime: '',
})
// 标准配套设备表头类型
interface columnsType {
  text: string
  value: string
  align: string
}
// 标准配套设备更换表头
const columns = ref<columnsType[]>([
  {
    text: '设备名称',
    value: 'name',
    align: 'center',
  },
  {
    text: '设备编号',
    value: 'bianhao',
    align: 'center',
  },
  {
    text: '型号',
    value: 'xinghao',
    align: 'center',
  },
  {
    text: '测量范围',
    value: 'fanwei',
    align: 'center',
  },
  {
    text: '使用部门',
    value: 'bumen',
    align: 'center',
  },
  {
    text: '检定时间',
    value: 'time',
    align: 'center',
  },
  {
    text: '检定结果',
    value: 'jieguo',
    align: 'center',
  },
  {
    text: '有效日期',
    value: 'riqi',
    align: 'center',
  },
])
// 标准配套设备更换查询条件
const listQuery = ref<object>({
  limit: 10,
  offset: 1,
})
// 标准配套设备更换表格loding
const loadingTable = ref(false)
// 申请文档表头
const columnsFiles = ref<object[]>([
  {
    text: '文件名称',
    value: 'name',
    align: 'center',
  },
  {
    text: '上传时间',
    value: 'name',
    align: 'center',
  },
  {
    text: '文件说明',
    value: 'name',
    align: 'center',
  },
  {
    text: '附件文档',
    value: 'name',
    align: 'center',
  },
])
// 标准配套设备更换表格分页
const changePage = () => {}
// 添加表格数据对象
const addList = ref({})
// 添加表格弹窗开关
const dialogVisible = ref(false)
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const rules = ref({
}) // 表单验证规则
// 上传请求
const uploadQuarterlyEvaluateFile = (file: File) => {
  const fd = new FormData()
  fd.append('multipartFile', file.file)
  UploadFile(fd).then((res) => {
    if (res.code === 200) {
      formInline.value.fileList = res.data
      // 重置当前验证
      ElMessage.success('文件上传成功')
    }
  })
}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning('只能上传一个文件')
}
// 移除时触发
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `确认移除${uploadFile.name}文件吗 ?`,
  ).then(
    () => true,
    () => false,

  )
}
// 点击文件预览
const uploadShow = (e: any) => {
  const URL = window.URL || window.webkitURL
  window.open(URL.createObjectURL(e.raw))
}
const testForm = ref({
  fileList: [],
  fileContent: '',
})
const handleFileChange = (files: any, fileList: any) => {
  testForm.value.fileList = fileList
  const reader = new FileReader()
  reader.readAsText(files.raw)
  // reader.onload = (e) => {
  //   testForm.value.fileContent = e.target!.result?.replace(
  //     /\n|\r\n/g,
  //     '<br/>',
  //   )
  // }
}
// 表格选中的数组
const SelectionList = ref<object[]>([])
// 标准实验室发生改变row类型
interface rowReturn {
  phone: string
  director: string
}
// 获取详情信息
const getInfo = () => {
  getStandardListDetail({ id: infoId.value }).then((res) => {
    Object.keys(res.data).map((item) => {
      if (typeof (res.data[item]) === 'number') {
        res.data[item] = res.data[item].toString()
      }
    })
    formInline.value = res.data
  })
}
if (pageType.value !== 'add') {
  getInfo()
}

// 提交
const submitForm = () => {
  return ruleFormRef.value
}
defineExpose({ submitForm })

// 点击顶部一排按钮
const getAddList = (item: string) => {
  if (item === '提交' || item === '保存') {
    console.log(item)
  }
  else {
    if (item === '同意') {
      applyList.value.select = '1'
    }
    else if (item === '驳回') {
      applyList.value.select = '2'
    }
    else {
      applyList.value.select = '3'
    }
    applyShow.value = true
  }
}
// 点击增加行
const addRoow = () => {
  Object.keys(addList.value).forEach(key => (addList.value[key] = ''))
  dialogVisible.value = true
}
// 点击关闭
const handleVisibleClose = () => {
  dialogVisible.value = false
}
// 点击弹窗的完成追加到表格数组中
const addPushList = () => {
  list.value.push(JSON.parse(JSON.stringify(addList.value)))
  handleVisibleClose()
}
// 标准配套设备更换表格删除行
const removeRow = () => {
  if (SelectionList.value.length > 0) {
    ElMessageBox.confirm(
      '确认删除选中的数据吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      // 删除行
      list.value = list.value.filter((item) => {
        return !SelectionList.value.includes(item)
      })
      ElMessage.success('删除成功')
    })
  }
  else {
    ElMessage.warning('请先选择需要删除的数据')
  }
}
// 表格多选框
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}
// 审批弹窗的关闭
const applyListClose = () => {
  applyShow.value = false
}
// 审批弹窗的提交
const applyListSubmit = () => {
  console.log(applyList.value)
  if (applyList.value.select == '') {
    return ElMessage.error('必须选择审批意见')
  }
  applyListClose()
}
// 审批弹窗关闭
const handleClose = () => {
  applyShow.value = false
}
</script>

<template>
  <app-container>
    <detail-page :title="`${$route.meta.title}-${textMap[pageType]}`">
      <template #btns>
        <el-button v-for="(item, index) in buttonArray" :key="index" type="primary" @click="getAddList(item)">
          {{ item }}
        </el-button>
        <el-button type="warning" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :inline="true"
        :model="formInline"
        label-position="left"
        label-width="auto"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="申请编号:" prop="constructionStandardProject">
              <el-input
                v-model.trim="formInline.constructionStandardProject"
                placeholder="建标项目"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请名称:" prop="constructionStandardProject">
              <el-input
                v-model.trim="formInline.constructionStandardProject"
                placeholder="建标项目"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请单位:" prop="constructionStandardProject">
              <el-input
                v-model.trim="formInline.constructionStandardProject"
                placeholder="建标项目"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人:" prop="constructionStandardProject">
              <el-input
                v-model.trim="formInline.constructionStandardProject"
                placeholder="建标项目"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item
              label="检修时间:"
              prop="constructionStandardUnitName"
            >
              <el-date-picker
                v-model="formInline.assessDate"
                type="datetime"
                placeholder="请选择考核日期"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD h:m:s"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="false" :gutter="20">
          <el-col :span="12">
            <el-form-item label="附件:">
              <el-upload
                v-model:file-list="fileList"
                enctype="multipart/form-data"
                :http-request="uploadQuarterlyEvaluateFile"
                :before-remove="beforeRemove"
                :on-exceed="handleExceed"
                :on-preview="uploadShow"
                :on-change="handleFileChange"
                :limit="1"
              >
                <el-button :disabled="pageType === 'detail'">
                  上传
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model.trim="formInline.remark"
                style="width: 500px;"
                placeholder="备注"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <div class="header">
      <div class="title">
        标准配套设备更换
      </div>
      <span class="btns">
        <el-button v-if="pageType !== 'detail'" type="primary">
          批量选择
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="addRoow">
          增加行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="info" @click="removeRow">
          删除行
        </el-button>
      </span>
    </div>
    <normal-table
      :data="list" :total="total" :columns="columns" :query="listQuery"
      :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
    />
    <div class="header">
      <div class="title">
        申请文档
      </div>
      <span class="btns">
        <el-button v-if="pageType !== 'detail'" type="primary">
          增加行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="info" @click="removeRow">
          删除行
        </el-button>
      </span>
    </div>
    <normal-table
      :data="list" :total="total" :columns="columnsFiles" :query="listQuery"
      :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
    />
    <div class="header">
      <div class="title">
        审批流程
      </div>
    </div>
  </app-container>
  <el-dialog
    v-model="dialogVisible"
    title="添加人员信息"
    width="30%"
    :before-close="handleVisibleClose"
    center
  >
    <el-form
      ref="addPersonListForm"
      label-position="left"
      label-width="100px"
      :model="addList"
      style="max-width: 460px;"
    >
      <el-form-item v-for="column in columns" :key="column.value" :label="column.text" :prop="addList[column.value]">
        <el-input v-model="addList[column.value]" />
      </el-form-item>
    </el-form>
    <el-button type="primary" class="dialog-button" @click="addPushList">
      完成
    </el-button>
  </el-dialog>
  <el-dialog
    v-model="applyShow"
    title="审批操作"
    width="50%"
    :before-close="handleClose"
  >
    <el-form
      ref="addPersonListForm"
      label-position="left"
      label-width="100px"
      :model="applyList"
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="审批意见:">
            <el-radio-group v-model="applyList.select" class="ml-4">
              <el-radio label="1" size="large">
                同意
              </el-radio>
              <el-radio label="2" size="large">
                驳回
              </el-radio>
              <el-radio label="3" size="large">
                拒绝
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="审批结论:">
            <el-input
              v-model="applyList.epilog"
              :rows="4"
              show-word-limit
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="审批人:">
            <el-input
              v-model="applyList.approval"
              placeholder="审批人"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="审批时间:">
            <el-input
              v-model="applyList.approvalTime"
              style="width: 100%;"
              placeholder="审批时间"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="applyListSubmit">
        提交
      </el-button>
      <el-button type="info" @click="handleClose">
        取消
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
// 样式
.top-info {
  width: 100%;
  height: 50px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10px;
  background-color: #fff;

  .title {
    width: 75%;
    text-align: center;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px;
  width: 100%;
  height: 6vh;
  background-color: rgb(233 231 231);
}

.info-content {
  padding: 15px;
  border-radius: 10px;
  background-color: #fff;
}

.dialog-buts {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

:deep .el-input .el-input--default .el-input--suffix {
  width: 200px !important;
}
</style>
