<!-- 设备检修列表新增、编辑、详情 -->
<script lang="ts" setup name="maintenanceDetail">
import { ref } from 'vue'
import { ElMessage, ElMessageBox, rowContextKey } from 'element-plus'
import type { FormInstance } from 'element-plus'
import dayjs from 'dayjs'
import { Row } from 'element-plus/es/components/table-v2/src/components'
import type { IlistPageAddTypes, columnsType, returnRowType } from '../checkList_interface'
import selectDeviceDialog from './selectDevice.vue'
import { addEquipmentApply, equipmentApplyInfo, failUpdateEquipmentApply, 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 { cancelApproval, fetchApproval } from '@/api/approval'
import { SCHEDULE } from '@/utils/scheduleDict'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import ApprovalRecord from '@/components/ApprovalRecord/ApprovalRecord.vue'
import useUserStore from '@/store/modules/user'
const approvalDialog = ref() // 审批对话ref
const user = useUserStore() // 用户信息
const approvalRecord = ref() // 审批流程组件ref
const infoId = ref('') // id
const from = ref('') // reject代表未通过-驳回
const buttonArray = ref<string[]>([])
const pageType = ref('add') // 页面类型: add,edit, detail
const decisionItem = ref('') // 同意、驳回、拒绝按钮权限
const approvalStatusName = ref('') // 审批状态名称
const taskId = ref('') // 任务id，用于同意、驳回、拒绝审批
const textMap: { [key: string]: string } = {
  add: '新建',
  edit: '编辑',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
// 表单验证规则
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'] }],
})

const ruleFormRef = ref<FormInstance>()
const useDeptList = ref<deptType[]>([]) // 使用部门列表
const usePersonList = ref<userType[]>([]) // 使用人列表
const usePersonOptions = ref<userType[]>([]) // 申请人列表（用户）--模糊搜索数据
const applyPersonLoading = ref(false)
const formInline = ref<IlistPageAddTypes>({
  acceptanceCheckId: '', // 检修申请id
  applyDesc: '', // 申请说明
  applyName: '', // 申请名称
  applyNo: '', // 申请编号
  applyPerson: '', // 申请人
  applyPersonName: '', // 申请人姓名
  applyType: '8', // 申请类型
  applyTypeName: '', // 申请类型名称
  applyUnit: '', // 申请单位
  applyUnitName: '', // 申请单位名称
  approvalStatus: '', // 审批状态
  approvalStatusName: '', // 审批状态名称
  createTime: '', // 创建时间
  createUser: '', // 创建人
  equipmentInfoList: [], // 设备详情列表
  equipmentList: [], // 设备列表
  id: '', // 主键
  isDel: '', // 删除id
  overhaulPerson: '',
  processId: '', // 审批id
  processResult: '',
  remark: '', // 备注
  taskId: '', // 任务id
  time: '',
  updateTime: '', // 更新时间
  version: '', // 版本号
})

// 审批弹窗开关
const applyShow = ref(false)
// 审批弹窗信息收集
const applyList = ref({
  select: '',
  epilog: '',
  approval: '',
  approvalTime: '',
})

// 检修设备列表表头
const columns = ref<columnsType[]>([
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
    required: true,
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
    width: '160px',
    required: true,
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
    required: false,
  },
  {
    text: '测量范围',
    value: 'mesureRange',
    align: 'center',
    required: false,
  },
  {
    text: '使用部门',
    value: 'useDeptName',
    align: 'center',
    required: false,
  },
  {
    text: '使用人',
    value: 'usePersonName',
    align: 'center',
    required: false,
  },
  {
    text: '管理状态',
    value: 'managerStateName',
    align: 'center',
    required: false,
  },
  {
    text: '有效日期',
    value: 'validDate',
    align: 'center',
    required: false,
    width: '120px',
  },
])

// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
// -------------------------路由参数------------------------------------
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
  }
}
if ($route.query && $route.query.from) {
  from.value = $route.query.from as string
}
// -------------------------------------------------------------------------

// 表格选中的数组
const SelectionList = ref<object[]>([])

// 获取详情信息
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
    formInline.value.equipmentInfoList = res.data.equipmentInfoList.map((item: any) => {
      return {
        ...item,
        validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : '',
      }
    })
  })
}
if (pageType.value !== 'add') {
  getInfo()
}
// 保存后的id
const addId = ref('')

// 保存
const save = async (formEl: FormInstance | undefined) => {
  if (!formInline.value.equipmentInfoList.length) {
    ElMessage.warning('要求设备检修列表不能为空')
    return
  }
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        // 处理数据
        if (formInline.value.equipmentInfoList && formInline.value.equipmentInfoList.length) {
          formInline.value.equipmentList = formInline.value.equipmentInfoList.map((item: any) => {
            return {
              equipmentId: item.id,
            }
          })
        }
        else {
          formInline.value.equipmentList = []
        }
        if (pageType.value === 'add') { // 新建
          addEquipmentApply(formInline.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('保存成功')
              addId.value = res.data
            }
          })
        }
        else if (pageType.value === 'edit') { // 编辑
          if (from.value === 'reject') { // 未通过-驳回的编辑
            failUpdateEquipmentApply(formInline.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                close()
              }
            })
          }
          else {
            updateEquipmentApply(formInline.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('保存成功')
                close()
              }
            })
          }
        }
      })
    }
  })
}
// 提交
const submit = () => {
  if (addId.value === '') {
    ElMessage.warning('请先保存')
  }
  else {
    submitEquipmentApply({ id: addId.value, formId: SCHEDULE.DEVICE_FIX_APPROVAL }).then((res) => {
      if (res.code === 200) {
        ElMessage.success('已提交')
        close()
      }
    })
  }
}

// ----------------------------------------------表格---------------------------------------
const dialogSelectDiviceVisible = ref(false)
// 点击批量增加
const batchIncrease = () => {
  dialogSelectDiviceVisible.value = true
}
// 选择设备对话框关闭
const closeDialog = () => {
  dialogSelectDiviceVisible.value = false
}

// 删除行
const removeRow = () => {
  if (SelectionList.value.length > 0) {
    // 删除行
    formInline.value.equipmentInfoList = formInline.value.equipmentInfoList.filter((item) => {
      return !SelectionList.value.includes(item)
    })
    // 删除给equipmentList重新赋值
    // formInline.value.equipmentList = []
    // formInline.value.equipmentInfoList.forEach((item: returnRowType, index: number) => {
    //   formInline.value.equipmentList.push({ equipmentId: item.id })
    // })
  }
  else {
    ElMessage.warning('请先选择需要删除的数据')
  }
}
// 表格多选框
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}

// 检修设备列表-选好设备了
const confirmSelectDevice = (row: returnRowType[]) => {
  row.forEach((item: returnRowType) => {
    // 只添加列表里不存在的
    const findIndex = formInline.value.equipmentInfoList.findIndex((i: any) => item.id === i.id)
    if (findIndex === -1) {
      formInline.value.equipmentInfoList.push(item)
    }
  })
}

// ----------------------------------------------------------------------------------

// 选好申请人 userId用户id
const changeSelectReceiver = (userId: string) => {
  // 在用户列表里找到选择的接收人的名字
  const name = usePersonList.value.find(item => item.id === userId)!.name
  // dataForm.value.reciever = name
}
// 选择器模糊查询--申请人
const remoteMethod = (query: string) => {
  if (query) {
    applyPersonLoading.value = true
    setTimeout(() => {
      applyPersonLoading.value = false
      usePersonOptions.value = usePersonList.value.filter((item) => {
        return item.name.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  }
  else {
    usePersonOptions.value = usePersonList.value
  }
}
// 获取部门列表
const fetchDeptTreeList = () => {
  getDeptTreeList().then((res) => {
  // 转成树结构
    useDeptList.value = toTreeList(res.data, '0', true)
  })
}
// 获取用户列表
const fetchUserList = () => {
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    usePersonList.value = res.data.rows
    usePersonOptions.value = res.data.rows
  })
}
// -------------------------------------------审批----------------------------------------
const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (pageType.value !== 'add') {
    if (processId) {
      fetchApproval(processId).then((res) => {
        approvalRecordData.value = res.data
      })
    }
    else {
      ElMessage.warning('流程实例id为空')
    }
  }
}
// 审批结束回调
const approvalSuccess = () => {
  close()
}
// 审批
const handleApprove = (val: string, title = '') => {
  if (val === '取消') {
    const params = {
      processInstanceId: formInline.value.processId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          close()
        })
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', taskId.value)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', taskId.value)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', taskId.value)
  }
}
// ---------------------------------------------------------------------------------------
onMounted(async () => {
  formInline.value.applyName = '设备检修申请' // 申请名称固定
  formInline.value.applyUnit = user.deptId // 申请单位
  formInline.value.applyUnitName = user.deptName // 申请单位名称
  formInline.value.applyPerson = user.id // 申请人
  formInline.value.applyPersonName = user.name // 申请人名称
  formInline.value.time = dayjs().format('YYYY-MM-DD HH:mm:ss') // 申请时间
  await fetchUserList()
  await fetchDeptTreeList()
  formInline.value.processId = $route.params.processId as string // 任务id
  decisionItem.value = $route.query.decisionItem as string // 同意、驳回、拒绝按钮权限
  taskId.value = $route.query.taskId as string // 流程实例id
  approvalStatusName.value = $route.params.approvalStatusName as string // 审批状态名称
  console.log(approvalStatusName.value)

  formInline.value.approvalStatusName = $route.params.approvalStatusName as string // 任务id
  if (formInline.value.approvalStatusName !== '草稿箱') {
    getApprovalRecord(formInline.value.processId) // 查询审批记录
  }
})
</script>

<template>
  <app-container>
    <detail-page :title="`${$route.meta.title}-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button>
        <el-button v-if="pageType === 'detail' && approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button>
        <el-button v-if="pageType === 'add'" type="primary" @click="submit">
          提交
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save(ruleFormRef)">
          保存
        </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="申请名称:">
              <el-input
                v-model.trim="formInline.applyName"
                :placeholder="pageType === 'detail' ? '' : '请输入申请名称'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请单位:">
              <!-- <dept-select
                v-model="formInline.applyUnit"
                :data="useDeptList"
                :placeholder="pageType === 'detail' ? '' : '请选择申请单位'"
                :disabled="pageType === 'detail'"
              /> -->
              <el-input
                v-model="formInline.applyUnitName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人:">
              <!-- <el-select
                v-model="formInline.applyPerson"
                :placeholder="pageType === 'detail' ? '' : '请选择申请人'"
                :disabled="pageType === 'detail'"
                style="width: 100%;"
                filterable
                remote
                remote-show-suffix
                :remote-method="remoteMethod"
                :loading="applyPersonLoading"
                @change="changeSelectReceiver"
              >
                <el-option
                  v-for="item in usePersonOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select> -->
              <el-input
                v-model="formInline.applyPersonName"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </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 HH:mm"
                :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'"
                type="textarea"
                autosize
              />
            </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" @click="batchIncrease">
          批量增加
        </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 v-if="pageType !== 'detail'" 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"
          show-overflow-tooltip
        >
          <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="formInline.approvalStatusName !== '草稿箱' && pageType !== 'add'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <select-device-dialog
      :dialog-select-divice-visible="dialogSelectDiviceVisible"
      :is-multi="true"
      @close-dialog="closeDialog"
      @updateDeviceConfirm="confirmSelectDevice"
    />
  </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>
