<!-- 新增或详情弹窗 设备借用处理新增编辑 -->
<script lang="ts" setup name="TemplateAdd">
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { EquipmentListRow } from './status-interface'
// import addRow from './addRow.vue'
import SelectDeviceDialog from './selectDeviceDialog.vue'
import type { deptType } from '@/views/device/standingBook/standingBook-interface'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { UploadFile } from '@/api/measure/file'
import { getUserList } from '@/api/system/user'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import type { userType } from '@/views/system/user/user-interface'
import { addStatus, detailStatus, submitStatus, updateRejectStatus, updateStatus } from '@/api/device/stateManage'
import useUserStore from '@/store/modules/user'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue' // 审批对话ref
import { SCHEDULE } from '@/utils/scheduleDict'
import { cancelApproval, fetchApproval } from '@/api/approval'
const approvalDialog = ref()
const user = useUserStore() // 用户信息
const $route = useRoute()
const userInfo = useUserStore()
const $router = useRouter()
const ruleFormRef = ref() // from组件
const title = ref('')
const name = ref('')
const isMulti = ref(false) // 是否批量添加(允许多选)
const dialogSelectDiviceVisible = ref(false) // 控制选择设备对话框显隐
const processId = ref('')
const decisionItem = ref('') // 同意、驳回、拒绝按钮权限
const taskId = ref('') // 任务id，用于同意、驳回、拒绝审批
const _approvalStatusName = ref('')
const statusTypeName = ref('') // 状态管理类型

// 状态管理
const ruleForm = ref({
  applyType: $route.query.applyType, // 申请类型
  remark: '', // 申请说明
  time: '', // 时间
  fileList: [] as any[], //	说明书
  applyUnit: '', // 申请单位
  applyPerson: '', // 申请人
  applyPersonName: '', // 申请人名称
  applyUnitName: '', // 申请单位名称
  applyNo: '', // 申请单编号
  applyName: '', // 申请单名称
  assetOriginValue: '', // 资产原值
  financialValue: '', // 财务净值
  equipmentNo: '', // 设备编号
  equipmentName: '', // 设备名称
  modelNo: '', // 型号
  equipmentSpecifications: '', // 设备规格
  manufacturingNo: '', // 出厂编号
  manufacturer: '', // 生产厂家
  equipmentId: '',
  equipmentList: [] as EquipmentListRow[],
  id: '',
})

const rules1 = ref<FormRules>({
  // applyUnit: [{ required: true, message: '申请单位必填', trigger: 'blur' }],
  // applyPerson: [{ required: true, message: '申请人必填', trigger: 'blur' }],
  equipmentNo: [{ required: true, message: '设备编号必填', trigger: 'blur' }],
  time: [{ required: true, message: '时间必填', trigger: 'blur' }],
  // applyName: [{ required: true, message: '申请单名称必填', trigger: 'blur' }],
  assetOriginValue: [{ required: true, message: '资产原值必填', trigger: 'blur' },
    { pattern: /(^[0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/, message: '要求不小于0，且最多保留两位小数', trigger: ['blur', 'change'] }],
  financialValue: [{ required: true, message: '财务净值必填', trigger: 'blur' },
    { pattern: /(^[0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/, message: '要求不小于0，且最多保留两位小数', trigger: ['blur', 'change'] }],
})
watch(() => ruleForm.value, (newVal) => {
  if (name.value === '详情') {
    if (newVal.applyUnit) {
      ruleFormRef.value.validateField('applyUnit')
    }
    if (newVal.applyPerson) {
      ruleFormRef.value.validateField('applyPerson')
    }
  }
}, {
  deep: true,
  immediate: true,
})
const usePersonList = ref<userType[]>([]) // 使用人列表
const useDeptList = ref<deptType[]>([]) // 使用部门列表
const useDeptListNoTree = ref([]) // 使用部门列表非树结构
// 获取字典
const fetchData = () => {
  // 获取用户列表
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    usePersonList.value = res.data.rows
  })
  // 获取部门列表
  getDeptTreeList().then((res) => {
    // 转成树结构
    useDeptList.value = toTreeList(res.data, '0', true)
    useDeptListNoTree.value = res.data
  })
}

// 弹窗初始化
const initDialog = (row: any) => {
  title.value = row.title
  name.value = row.name
  fetchData()
  // 状态管理
  if ($route.query.title !== '新建') {
    detailStatus({ id: $route.params.id }).then((res) => {
      processId.value = res.data.processId // 流程id存在的时候赋值
      ruleForm.value = res.data
      ruleForm.value.applyUnit = res.data.applyUnit
      ruleForm.value.equipmentNo = res.data.applyNo
      ruleForm.value.equipmentName = res.data.equipmentName
      ruleForm.value.time = res.data.time
      if (res.data.approvalStatusName !== '草稿箱') {
        getApprovalRecord(res.data.processId) // 查询审批记录
      }
    })
  }
}
// 关闭弹窗
const close = () => {
  $router.back()
}

// -----------------------------------------审批----------------------------------------
const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (title.value !== '新建') {
    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: processId.value!,
      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)
  }
}
// ------------------------------------------------------------------------------------------

// 保存
const statusManageSave = async (formEl1: FormInstance | undefined) => {
  if (!formEl1) { return }
  await formEl1.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        const loading = ElLoading.service({
          lock: true,
          background: 'rgba(255, 255, 255, 0.8)',
        })
        if (title.value === '新建') { // 新建
          ruleForm.value.equipmentList[0].assetOriginValue = ruleForm.value.assetOriginValue
          ruleForm.value.equipmentList[0].financialValue = ruleForm.value.financialValue
          addStatus(ruleForm.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('操作成功!')
              ruleForm.value.id = res.data
              loading.close()
            }
            else {
              ElMessage.warning(res.message)
              loading.close()
            }
          })
        }
        else { // 编辑
          if (_approvalStatusName.value === '未通过-驳回') {
            if (ruleForm.value.equipmentList && ruleForm.value.equipmentList[0]) {
              ruleForm.value.equipmentId = ruleForm.value.equipmentList[0].equipmentId
              // delete ruleForm.value.equipmentList
            }
            updateRejectStatus(ruleForm.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('操作成功!')
                loading.close()
                $router.back()
              }
              else {
                ElMessage.warning(res.message)
                loading.close()
              }
            })
          }
          else { // 草稿箱、已取消
            if (ruleForm.value.equipmentList && ruleForm.value.equipmentList[0]) {
              ruleForm.value.equipmentId = ruleForm.value.equipmentList[0].equipmentId
              // delete ruleForm.value.equipmentList
            }
            updateStatus(ruleForm.value).then((res) => {
              if (res.code === 200) {
                ElMessage.success('操作成功!')
                loading.close()
                $router.back()
              }
              else {
                ElMessage.warning(res.message)
                loading.close()
              }
            })
          }
        }
      })
    }
  })
}

// 提交
const statusManageSubmit = async (formEl1: FormInstance | undefined) => {
  if (ruleForm.value.id === '') {
    ElMessage.warning('请先保存再提交!')
    return
  }
  if (!formEl1) { return }
  await formEl1.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认提交吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        submitStatus({
          formId: $route.query.formId as string,
          id: ruleForm.value.id,
          processId: '',
        }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('操作成功!')
            $router.back()
          }
          else {
            ElMessage.warning(res.message)
          }
        })
      })
    }
  })
}

const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  const files = event.target.files
  if (files.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    for (var i = 0; i < files.length; i++) {
      fd.append('multipartFile', files[i])
    }
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      console.log(res)
      if (res.code === 200 && res.data.length >= 1) {
        for (const item of res.data) {
          ruleForm.value.fileList.push({
            assetId: '',
            fileName: item,
            minioFileName: item,
          // id: '',
          })
        }
        ruleFormRef.value?.clearValidate('minioFileName')
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        loading.close()
        ElMessage.error(res.message)
      }
    })
  }
}

const del = (index: any) => {
  ruleForm.value.fileList.splice(index, 1)
}
const upload = () => {
  fileRef.value.click()
}

// 设备状态管理
const addRowBtn = () => {
  dialogSelectDiviceVisible.value = true // 选择设备对话框显隐
  isMulti.value = false // 是否单选, false单选、true表格多选
}

// 选择设备对话框关闭
const closeDialog = () => {
  dialogSelectDiviceVisible.value = false
}

// 选择好设备了, 添加选好的设备到表格中
const updateDeviceConfirm = (val: any) => {
  // // 如果是状态管理
  const device = val[0]
  ruleForm.value.equipmentNo = device.equipmentNo // 设备编号
  ruleForm.value.equipmentName = device.equipmentName // 设备名称
  ruleForm.value.modelNo = device.modelNo // 型号
  ruleForm.value.equipmentSpecifications = device.equipmentSpecifications as string
  ruleForm.value.manufacturingNo = device.manufacturingNo as string
  ruleForm.value.manufacturer = device.manufacturer as string
  ruleFormRef.value.clearValidate('equipmentNo')
  // 赋值
  ruleForm.value.equipmentList = [{
    equipmentId: device.id as string,
  }]
  return false
}
onMounted(() => {
  initDialog($route.query)
  const tempName = name.value.substring(2, 4)
  statusTypeName.value = tempName
  ruleForm.value.applyName = `设备${tempName}申请` // 申请名称固定
  ruleForm.value.applyUnit = user.deptId // 申请单位
  ruleForm.value.applyUnitName = user.deptName // 申请单位名称
  ruleForm.value.applyPerson = user.id // 申请人
  ruleForm.value.applyPersonName = user.name // 申请人名称
  decisionItem.value = $route.query.decisionItem as string // 同意、驳回、拒绝按钮权限
  taskId.value = $route.query.taskId as string // 流程实例id
  _approvalStatusName.value = $route.query.approvalStatusName as string // 审批状态名称
})
</script>

<template>
  <app-container style="overflow: hidden;">
    <detail-page :title="`${name}-${title}`">
      <template #btns>
        <el-button v-if="title === '详情' && _approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button>
        <el-button v-if="title === '详情' && _approvalStatusName === '待审批' && decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button>
        <el-button v-if="title === '详情' && _approvalStatusName === '待审批' && decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button>
        <el-button v-if="title === '详情' && _approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button>
        <el-button v-if="title === '新建'" type="primary" @click="statusManageSubmit(ruleFormRef)">
          提交
        </el-button>
        <el-button v-if="title === '新建' || title === '编辑'" type="primary" @click="statusManageSave(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <!-- 状态管理 -->
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules1" label-position="right" label-width="110px" class="form" :class="[title === '详情' ? 'isDetail' : '']">
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="申请单编号" prop="applyNo">
              <el-input v-model.trim="ruleForm.applyNo" :placeholder="title === '详情' ? '' : '系统自动生成'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请单名称" prop="applyName">
              <el-input v-model.trim="ruleForm.applyName" disabled :placeholder="title === '详情' ? '' : '申请单名称'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人" prop="applyPerson">
              <el-select v-model="ruleForm.applyPerson" :placeholder="title === '详情' ? '' : '申请人'" disabled 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-col :span="6">
            <el-form-item label="申请单位" prop="applyUnit">
              <dept-select v-model="ruleForm.applyUnit" :data="useDeptList" :placeholder="title === '详情' ? '' : '申请单位'" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="设备编号" prop="equipmentNo" class="equipmentNo">
              <el-input v-model.trim="ruleForm.equipmentNo" :placeholder="title === '详情' ? ' ' : '设备编号'" disabled>
                <template v-if="title !== '详情'" #append>
                  <el-button type="primary" size="small" @click="addRowBtn">
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model.trim="ruleForm.equipmentName" :placeholder="title === '详情' ? ' ' : '设备名称'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号" prop="modelNo">
              <el-input v-model.trim="ruleForm.modelNo" :placeholder="title === '详情' ? ' ' : '型号'" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="设备规格" prop="equipmentSpecifications">
              <el-input v-model.trim="ruleForm.equipmentSpecifications" :placeholder="title === '详情' ? '' : '设备规格'" disabled />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="出厂编号" prop="manufacturingNo">
              <el-input v-model.trim="ruleForm.manufacturingNo" :placeholder="title === '详情' ? ' ' : '出厂编号'" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model.trim="ruleForm.manufacturer" :placeholder="title === '详情' ? ' ' : '生产厂家'" disabled />
            </el-form-item>
          </el-col>
          <el-col v-if="name.substring(2, 4) !== '处置'" :span="6">
            <el-form-item :label="`${name.substring(2, 4)}时间`" prop="time">
              <el-date-picker
                v-model="ruleForm.time" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD hh:mm" :disabled="title === '详情'"
                :placeholder="title === '详情' ? '' : `${name.substring(2, 4)}时间`"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <!-- 处置的报废时间-后端通知暂时隐藏 -->
          <!-- <el-col v-else :span="6">
            <el-form-item label="报废时间" prop="time">
              <el-date-picker
                v-model="ruleForm.time" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD hh:mm" :disabled="title === '详情'"
                placeholder="报废时间"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col> -->
          <el-col v-if="name.substring(2, 4) === '处置'" :span="6">
            <el-form-item label="资产原值(元)" prop="assetOriginValue">
              <el-input v-model.trim="ruleForm.assetOriginValue" :placeholder="title === '详情' ? '' : '资产原值'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col v-if="name.substring(2, 4) === '处置'" :span="6">
            <el-form-item label="财务净值(元)" prop="financialValue">
              <el-input v-model.trim="ruleForm.financialValue" :placeholder="title === '详情' ? '' : '财务净值'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="申请理由" prop="remark">
              <el-input v-model.trim="ruleForm.remark" type="textarea" autosize :placeholder="title === '详情' ? '' : '申请理由'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="附件" prop="minioFileName">
              <el-button v-if="title !== '详情'" type="primary" :disabled="title === '详情'" @click="upload">
                上传
              </el-button>
              <div style="display: flex;">
                <show-photo v-for="(item, index) in ruleForm.fileList" :key="item" :index="index" :minio-file-name="item.minioFileName || ''" style="display: inline-block;margin: 0 10px;">
                  <span v-if="title !== '详情'" class="photo-close" @click="del(index)">×</span>
                </show-photo>
              </div>
              <input v-show="title === ''" ref="fileRef" multiple type="file" @change="onFileChange">
              <span v-if="title === '详情' && !ruleForm.fileList[0]?.minioFileName">无</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block v-if="title !== '新建' && _approvalStatusName !== '草稿箱'" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <select-device-dialog
      :status-type-name="statusTypeName"
      :dialog-select-divice-visible="dialogSelectDiviceVisible"
      :is-multi="isMulti"
      @close-dialog="closeDialog"
      @updateDeviceConfirm="updateDeviceConfirm"
    />
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
  </app-container>
</template>

<style lang="scss" scoped>
.equipmentNo {
  position: relative;

  .equipmentNo-item {
    position: absolute;
    top: 0;
    right: 0;
  }
}

:deep(.el-checkbox__label) {
  display: none;
}

.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>
