<script lang="ts" setup name="maintenanceAdd">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { addEquipmentApply, equipmentApplyInfo, submitEquipmentApply, updateEquipmentApply } from '@/api/device/checkList'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import { getUserList } from '@/api/system/user'
import type { deptType } from '@/views/device/standingBook/standingBook-interface'
import type { userType } from '@/views/system/user/user-interface'
import { submitApproval } from '@/api/approval'
import { SCHEDULE } from '@/utils/scheduleDict'
import addRow from '@/views/device/stateManage/components/addRow.vue'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
const infoId = ref('') // id
const buttonArray = ref<string[]>([])
const pageType = ref('add') // 页面类型: add,edit, detail
const textMap: { [key: string]: string } = {
  add: '新建',
  edit: '编辑',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
const $route = useRoute()
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 useDeptList = ref<deptType[]>([]) // 使用部门列表
const usePersonList = ref<userType[]>([]) // 使用人列表
// 逻辑代码
const formInline = ref({
  acceptanceCheckId: '',
  applyDesc: '',
  applyName: '',
  applyNo: '',
  applyPerson: '',
  applyPersonName: '',
  applyType: '8', //
  applyTypeName: '',
  applyUnit: '',
  applyUnitName: '',
  approvalStatus: '', // 审批状态
  approvalStatusName: '', // 审批状态名称
  createTime: '',
  createUser: '',
  equipmentInfoList: [],
  equipmentList: [],
  id: null, // 主键
  isDel: null,
  overhaulPerson: '',
  processId: '', // 审批id
  processResult: '',
  remark: '',
  taskId: '',
  time: '',
  updateTime: '', // 更新时间
  version: '',
})
// 审批弹窗信息收集类型
interface ListType {
  equipmentName: string
  equipmentNo: string
  modelNo: string
  mesureRange: string
  useDeptName: string
  usePersonName: string
  managerStateName: string
  validDate: string
  equipmentSpecifications: string
  manufacturingNo: string
  manufacturer: string
}
// 数据
const list = ref<ListType[]>([])
// 审批弹窗开关
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
  required: boolean
  width?: string
}
// 标准配套设备更换表头
const columns = ref<columnsType[]>([
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
    required: true,
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
    required: true,
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
    required: true,
  },
  {
    text: '测量范围',
    value: 'mesureRange',
    align: 'center',
    required: true,
  },
  {
    text: '使用部门',
    value: 'useDeptName',
    align: 'center',
    required: true,
  },
  {
    text: '使用人',
    value: 'usePersonName',
    align: 'center',
    required: true,
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    align: 'center',
    required: true,
  },
  {
    text: '有效日期',
    value: 'validDate',
    align: 'center',
    required: true,
    width: '160px',
  },
])
// 标准配套设备更换查询条件
const listQuery = ref<object>({
  limit: 10,
  offset: 1,
})
// 标准配套设备更换表格loding
const loadingTable = ref(false)
// 标准配套设备更换表格分页
const changePage = () => {}
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
// 表单验证规则
const rules = ref({
  applyName: [{ required: true, message: '申请名称不能为空', trigger: ['blur', 'change'] }],
  applyUnit: [{ required: true, message: '申请单位不能为空', trigger: ['blur', 'change'] }],
  applyPerson: [{ required: true, message: '申请人不能为空', trigger: ['blur', 'change'] }],
  time: [{ required: true, message: '检修时间不能为空', trigger: ['blur', 'change'] }],
})
// 获取部门列表
getDeptTreeList().then((res) => {
  // 转成树结构
  useDeptList.value = toTreeList(res.data, '0', true)
})
// 获取用户列表
getUserList({ offset: 1, limit: 99999 }).then((res) => {
  usePersonList.value = res.data.rows
})
// 审批结束回调
const approvalSuccess = () => {
}

// 表格选中的数组
const SelectionList = ref<object[]>([])
// 标准实验室发生改变row类型
interface rowReturn {
  phone: string
  director: string
}
// 取消
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
  }
}
// 获取详情信息
const getInfo = () => {
  equipmentApplyInfo({ 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()
}
// 保存后的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(() => {
          addEquipmentApply(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(() => {
          updateEquipmentApply(formInline.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('保存成功')
              addId.value = res.data.id
            }
          })
        })
      }
    })
  }
  else if (item === '提交') {
    if (addId.value === '') {
      ElMessage.warning('请先保存')
    }
    else {
      submitEquipmentApply({ id: addId.value, formId: SCHEDULE.DEVICE_FIX_APPROVAL }).then((res) => {
        if (res.code === 200) {
          close()
        }
      })
    }
  }
  else {
    clickBtn(item)
  }
}

const addRowRef = ref()
// 点击增加行
const addRoow = () => {
  // list.value.push(JSON.parse(JSON.stringify(addList.value)))
  addRowRef.value.initDialog({ title: '' })
}

// 标准配套设备更换表格删除行
const removeRow = () => {
  if (SelectionList.value.length > 0) {
    ElMessageBox.confirm(
      '确认删除选中的数据吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      // 删除行
      formInline.value.equipmentInfoList = formInline.value.equipmentInfoList.filter((item) => {
        return !SelectionList.value.includes(item)
      })
      ElMessage.success('删除成功')
    })
  }
  else {
    ElMessage.warning('请先选择需要删除的数据')
  }
}
// 表格多选框
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}
// 设备列表对象类型
interface returnRowType {
  id: string
}
// 设备列表添加
const addRowMethods = (row: Array) => {
  row.forEach((item: returnRowType, index: string) => {
    formInline.value.equipmentList.push({ equipmentId: item.id })
  })
  // 设备状态
  formInline.value.equipmentInfoList.push(...row)
}
// 审批弹窗的关闭
const applyListClose = () => {
  applyShow.value = false
}
// 审批弹窗的提交
const applyListSubmit = () => {
  console.log(applyList.value)
  if (applyList.value.select == '') {
    return ElMessage.error('必须选择审批意见')
  }
  applyListClose()
}
onMounted(async () => {
  formInline.value.processId = $route.params.processId as string // 任务id
})
// 审批弹窗关闭
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, 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">
          <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="applyUnit">
              <dept-select
                v-model="formInline.applyUnit"
                :data="useDeptList"
                :placeholder="pageType === 'detail' ? '' : '请选择申请单位'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人:" prop="applyPerson">
              <el-select
                v-model="formInline.applyPerson"
                :placeholder="pageType === 'detail' ? '' : '请选择申请人'"
                :disabled="pageType === 'detail'"
                style="width: 100%;"
              >
                <el-option
                  v-for="item in usePersonList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="检修时间:" prop="time">
              <el-date-picker
                v-model="formInline.time"
                type="datetime"
                style="width: 100%;"
                :placeholder="pageType === 'detail' ? '' : '请选择检修时间'"
                format="YYYY/MM/DD HH:mm"
                value-format="YYYY-MM-DD h:m"
                :disabled="pageType === 'detail'"
              />
            </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"
                :placeholder="pageType === 'detail' ? '' : '请填写备注'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="检修设备列表">
      <template v-if="pageType !== 'detail'" #btns>
        <!-- <el-button v-if="pageType !== 'detail'" type="primary">
          批量选择
        </el-button> -->
        <el-button type="primary" @click="addRoow">
          增加行
        </el-button>
        <el-button type="info" @click="removeRow">
          删除行
        </el-button>
      </template>
      <el-table
        :data="formInline.equipmentInfoList"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <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>
        </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" />
    <!-- 借用设备列表 -->
    <add-row ref="addRowRef" @add="addRowMethods" />
  </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 255 255);
}

.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      display: none;
    }
  }
}
</style>
