<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 '../checkList_interface'
import checkList from './checkList.vue'
import { getStaffList } from '@/api/measure/person'
import { getTypeSelect } from '@/api/system/price'
import { acceptanceCheckInfo, addAcceptanceCheck, equipmentApplyInfo, submitAcceptanceCheck, updateAcceptanceCheckInfo } from '@/api/device/checkList'
import { UploadFile } from '@/api/measure/file'
import { submitApproval } from '@/api/approval'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
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({
  acceptanceCheckId: '',
  applyDesc: '',
  applyName: '',
  applyNo: '',
  applyPerson: '',
  applyPersonName: '',
  applyType: '9',
  applyTypeName: '',
  applyUnit: '',
  applyUnitName: '',
  approvalStatus: '',
  approvalStatusName: '',
  createTime: '',
  createUser: '',
  equipmentInfoList: [],
  equipmentList: [],
  fileList: [
    {
      applyId: '',
      createTime: '',
      createUser: '',
      fileName: '',
      id: '',
      isDel: '',
      minioFileName: '',
      remark: '',
      updateTime: '',
    },
  ],
  id: '',
  isDel: '',
  overhaulPerson: '',
  processId: '',
  processResult: '',
  remark: '',
  taskId: '',
  time: '',
  updateTime: '',
  version: '',
})
// 审批弹窗信息收集类型
interface checkIdObjectType {
  applyName: string
  applyPersonName: string
  time: string
  applyNo: string
}
// 获取到检修申请列表数据
const checkIdObject = ref<checkIdObjectType>({
  applyName: '',
  applyPersonName: '',
  time: '',
  applyNo: '',
})
// 检修设备列表数据
const list = ref<object[]>([])
// 审批弹窗开关
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
  width?: string
  required: boolean
}
// 标准配套设备更换表头
const columns = ref<columnsType[]>([
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
    required: false,
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
    required: false,
  },
  {
    text: '检修结果',
    value: 'overhaulResult',
    align: 'center',
    required: true,
  },
  {
    text: '检修意见',
    value: 'overhaulIdea',
    width: '450px',
    align: 'center',
    required: true,
  },
])
const checkListRef = ref()
// 检修申请编号按钮
const selectPerson = () => {
  checkListRef.value.initDialog()
}
// 标准配套设备更换表格分页
const changePage = () => {}

// 添加表格数据对象
const addList = ref({})
// 检修结果下拉框
const options = ref([
  { name: '已维修,可用', id: '1' },
  { name: '已维修,未修好', id: '2' },
  { name: '未维修', id: '3' },
  { name: '其他', id: '4' },
])
// 添加表格弹窗开关
const dialogVisible = ref(false)
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const rules = ref({
  applyName: [{ required: true, message: '验收单名称不能为空', trigger: ['blur', 'change'] }],
  acceptanceCheckId: [{ required: true, message: '检修申请编号不能为空', trigger: ['blur', 'change'] }],
  overhaulPerson: [{ required: true, message: '检修保养人不能为空', trigger: ['blur', 'change'] }],
  time: [{ required: true, message: '检修时间不能为空', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 审批流程
const approvalActivities = [
  {
    name: '张三',
    deptName: '审计局',
    content: '同意',
    timestamp: '2018-04-15 08:00:00',
  },
  {
    name: '张三',
    content: 'Approved',
    timestamp: '2018-04-13',
  },
  {
    name: '张三',
    content: 'Success',
    timestamp: '2018-04-11',
  },
]
// 点击文件预览
const uploadShow = (e: any) => {
  const URL = window.URL || window.webkitURL
  window.open(URL.createObjectURL(e.raw))
}
const onFileChange = (event: any) => {
  // 原生上传
  console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        formInline.value.fileList[0].minioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
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 = () => {
  acceptanceCheckInfo({ id: infoId.value }).then((res) => {
    Object.keys(res.data).map((item) => {
      if (typeof (res.data[item]) === 'number') {
        res.data[item] = res.data[item].toString()
      }
    })
    checkIdObject.value.applyNo = res.data.checkApplyNo
    checkIdObject.value.applyName = res.data.checkApplyName
    formInline.value = res.data
  })
}
if (pageType.value !== 'add') {
  getInfo()
}
const fileRef = ref() // 文件上传input

// 点击上传文件按钮
const upload = () => {
  fileRef.value.click()
}
// 审批结束回调
const approvalSuccess = () => {
  getInfo()
}
// 提交
const submitForm = () => {
  return ruleFormRef.value
}
defineExpose({ submitForm })
// 取消
const handleCancel = () => {
  const params = {
    taskId: formInline.value.taskId!,
    comments: '',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      submitApproval('revoke', params).then((res) => {
        ElMessage({
          type: 'success',
          message: '取消成功',
        })
      })
    })
}
const approvalDialog = ref()
// 点击数据后的操作按钮
const clickBtn = (buttonType: string) => {
  switch (buttonType) {
    case '同意':
      approvalDialog.value.initDialog('agree', formInline.value.taskId)
      break
    case '驳回':
      approvalDialog.value.initDialog('reject', formInline.value.taskId)
      break
    case '拒绝':
      approvalDialog.value.initDialog('refuse', formInline.value.taskId)
      break
    case '取消':
      handleCancel()
      break
  }
}
// 保存后的id
const addId = ref('')
// 点击顶部一排按钮
const getAddList = async (item: string, formEl: FormInstance | undefined) => {
  if (item === '保存' && pageType.value === 'add') {
    if (!formEl) { return }
    await formEl.validate((valid, fields) => {
      if (valid) {
        ElMessageBox.confirm(
          '确认保存吗？',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          },
        ).then(() => {
          addAcceptanceCheck(formInline.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('保存成功')
              addId.value = res.data.id
            }
          })
        })
      }
    })
  }
  else if (item === '保存' && pageType.value === 'edit') {
    if (!formEl) { return }
    await formEl.validate((valid, fields) => {
      if (valid) {
        ElMessageBox.confirm(
          '确认保存吗？',
          '提示',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          },
        ).then(() => {
          updateAcceptanceCheckInfo(formInline.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('保存成功')
              addId.value = res.data.id
            }
          })
        })
      }
    })
  }
  else if (item === '提交') {
    if (addId.value === '') {
      ElMessage.warning('请先保存')
    }
    else {
      submitAcceptanceCheck({ id: addId.value, formId: SCHEDULE.DEVICE_FIX_APPROVAL }).then((res) => {
        if (res.code === 200) {
          close()
        }
      })
    }
  }
  else {
    clickBtn(item)
  }
}

// 标准实验室发生改变row类型
interface objectReturn {
  id: string
  applyName: string
  applyPersonName: string
  time: string
  applyNo: string
  equipmentId: string
}
// 选择完负责人的函数
const confirmPerson = (object: objectReturn) => {
  formInline.value.acceptanceCheckId = object.id
  checkIdObject.value = object
  // 获取到详情
  equipmentApplyInfo({ id: object.id }).then((res) => {
    res.data.equipmentInfoList.map((item: objectReturn) => {
      if (item.id) {
        item.equipmentId = item.id
      }
      // 如果选择的没有id则就让装置数组置空
      else {
        return formInline.value.equipmentList = []
      }
    })
    formInline.value.equipmentList = res.data.equipmentInfoList
  })
}
// 审批弹窗的关闭
const applyListClose = () => {
  applyShow.value = false
}
// 审批弹窗的提交
const applyListSubmit = () => {
  console.log(applyList.value)
  if (applyList.value.select == '') {
    return ElMessage.error('必须选择审批意见')
  }
  applyListClose()
}
// 审批弹窗关闭
const handleClose = () => {
  applyShow.value = false
}
onMounted(async () => {
  formInline.value.processId = $route.params.processId as string // 任务id
})
</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, ruleFormRef)">
          {{ item }}
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="formInline"
        label-position="right"
        label-width="110px"
        :rules="rules"
      >
        <el-row :gutter="20" class="marg">
          <el-col :span="6">
            <el-form-item label="验收单编号:">
              <el-input
                v-model.trim="formInline.applyNo"
                :placeholder="pageType === 'detail' ? '' : '验收单编号、自动生成'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="验收单名称:" prop="applyName">
              <el-input
                v-model.trim="formInline.applyName"
                :placeholder="pageType === 'detail' ? '' : '请输入验收单名称'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检修申请编号:" prop="acceptanceCheckId">
              <el-input
                v-model="checkIdObject.applyNo"
                :placeholder="pageType === 'detail' ? '无' : '请选择检修申请编号'"
                :disabled="pageType === 'detail'"
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="selectPerson"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="检修申请名称:" prop="constructionStandardProject">
              <el-input
                v-model.trim="checkIdObject.applyName"
                :placeholder="pageType === 'detail' ? '' : '请填写检修申请名称'"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="marg">
          <el-col :span="6">
            <el-form-item label="检修保养人:" prop="overhaulPerson">
              <el-input
                v-model.trim="formInline.overhaulPerson"
                :placeholder="pageType === 'detail' ? '' : '请填写检修保养人'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="检修日期:"
              prop="time"
            >
              <el-date-picker
                v-model="formInline.time"
                style="width: 100%;"
                type="date"
                :placeholder="pageType === 'detail' ? '' : '请选择检修日期'"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="marg">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model.trim="formInline.remark"
                :placeholder="pageType === 'detail' ? '' : '请填写备注'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" class="marg">
          <el-col :span="14">
            <el-form-item label="附件:">
              <show-photo v-if="formInline.fileList[0].minioFileName" :minio-file-name="formInline.fileList[0].minioFileName" />
              <span v-else-if="pageType === 'detail'">无</span>
              <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
              <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': formInline.fileList[0].minioFileName === '' ? '0px' : '20px' }" @click="upload">
                {{ formInline.fileList[0].minioFileName === '' ? '上传' : '更换附件' }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="检修设备列表">
      <el-table
        :data="formInline.equipmentList ? formInline.equipmentList : formInline.checkList"
        border
        style="width: 100%;"
      >
        <el-table-column align="center" label="序号" width="60" type="index" />
        <el-table-column v-for="(item, index) in columns" :key="index" align="center" :label="item.text" :width="item.width" :prop="item.value">
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <el-input v-if="item.text === '检修意见' && pageType !== 'detail'" v-model="scope.row[item.value]" :placeholder="`${item.text}`" class="input" />
            <el-select
              v-if="item.text === '检修结果'"
              v-model="scope.row[item.value]"
              clearable
              placeholder="计划编号"
              size="default"
              :disabled="pageType === 'detail'"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
    <detail-block v-if="pageType === 'detail'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record :process-id="formInline.processId" />
    </detail-block>
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <!-- 选择用户列表组件 -->
    <check-list ref="checkListRef" @add="confirmPerson" />
  </app-container>
</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;
  margin-top: 10px;
  background-color: rgb(255 253 253);
}

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

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