<script lang="ts" setup name="EditExpire">
import type { Ref } from 'vue'
import { nextTick, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import device from './device.vue'
import task from './task.vue'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
import { addRemind, getList, updateRemind } from '@/api/system/expire'
// ----------------------- 以下是字段定义 emits props ---------------------
const emits = defineEmits(['closeRefresh'])

const dialogVisible = ref(false)
const dialogStatus = ref('新建')
const userStore = useUserStore()
const data = ref({
  createDeptId: '',
  createDeptName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  id: '',
  remindName: '',
  remindTime: 30,
  updateTime: '',
  remindType: '1',
  taskIds: [] as string[],
  taskNames: [] as string[],
  equipmentNames: [] as string[],
  modelIds: [] as string[],
  equipmentExt: [] as string[],
  taskExt: [] as string[],

})
const resetForm = () => {
  for (const i in data.value) {
    data.value[i] = ''
  }
  data.value.remindTime = 30
  data.value.remindType = '1'
  data.value.taskIds = [] as string[]
  data.value.taskNames = [] as string[]
  data.value.equipmentNames = [] as string[]
  data.value.modelIds = [] as string[]
  data.value.equipmentExt = [] as string[]
  data.value.taskExt = [] as string[]
}
// ---------------表单提交--------------------------------
// 表单对象
const dataFormRef = ref<FormInstance>()
const rules = ref<FormRules>({
  remindName: [{ required: true, message: '提醒名称必填', trigger: ['blur', 'change'] }],
  remindType: [{ required: true, message: '到期提醒类型必选', trigger: ['blur', 'change'] }],
  modelIds: [{ required: true, message: '设备必选', trigger: ['blur', 'change'] }],
  taskIds: [{ required: true, message: '任务必选', trigger: ['blur', 'change'] }],
  remindTime: [{ required: true, message: '提醒时间必选', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 表单提交
function submitForm() {
  if (dataFormRef) {
    dataFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        if (dialogStatus.value === '新建') {
          addRemind(data.value).then((res) => {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            emits('closeRefresh')
          })
        }
        else {
          updateRemind(data.value).then((res) => {
            ElMessage.success('修改成功')
            dialogVisible.value = false
            emits('closeRefresh')
          })
        }
      }
    })
  }
}

// ----------初始化、关闭对话框相关-----------------
function initDialog(row: any, status: string) {
  dialogVisible.value = true
  resetForm()
  if (status === 'create') {
    dialogStatus.value = '新建'
    nextTick(() => {
      dataFormRef.value?.resetFields()
    })

    data.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    data.value.createUserId = userStore.id
    data.value.createUserName = userStore.name
    // 获取当前用户所在单位
    data.value.createDeptId = userStore.deptId
    data.value.createDeptName = userStore.deptName
    // getUserDept().then((res) => {
    //   // fullName
    //   data.value.createDeptId = res.data.id
    //   data.value.createDeptName = res.data.fullName
    // })
  }
  else {
    data.value = JSON.parse(JSON.stringify(row))
    dialogStatus.value = '编辑'
    data.value.equipmentExt = JSON.parse(row.equipmentExt)
    data.value.taskExt = JSON.parse(row.taskExt)
  }
}

// 关闭并刷新
function closeRefresh() {
  dialogVisible.value = false
  emits('closeRefresh')
}
// 关闭弹窗
function dialogClose() {
  dialogVisible.value = false
}
// ----------------------- 以下是暴露的方法内容 ----------------------------
defineExpose({ initDialog })

// 选择设备
const deviceRef = ref()
const selectDevice = () => {
  deviceRef.value.initDialog()
}
// 确认设备
const confirmDevice = (list: any[]) => {
  list.forEach((item: any) => {
    if (!data.value.modelIds.includes(item.id)) {
      data.value.equipmentExt.push(`${item.equipmentName}/${item.model}/${item.helpInstruction}`)
      data.value.modelIds.push(item.id)
    }
  })
}
const removeDeviceStr = ref()
const removeDevice = (device: string) => {
  removeDeviceStr.value = device
}
watch(() => data.value.equipmentExt, (newVal, oldVal) => {
  if (newVal && oldVal) {
    if (newVal.length < oldVal.length) {
      const index = oldVal.indexOf(removeDeviceStr.value)
      data.value.modelIds = data.value.modelIds.filter((item, cindex) => cindex !== index)
    }
  }
}, {
  deep: true,
})
// 选择任务
const taskRef = ref()
const selectTask = () => {
  taskRef.value.initDialog()
}
// 确认设备
const confirmTask = (list: any[]) => {
  list.forEach((item: any) => {
    if (!data.value.taskIds.includes(item.id)) {
      data.value.taskExt.push(`${item.taskName}/${item.createTime}`)
      data.value.taskIds.push(item.id)
    }
  })
}
const removeTaskStr = ref()
const removeTask = (task: string) => {
  removeTaskStr.value = task
}
watch(() => data.value.taskExt, (newVal, oldVal) => {
  if (newVal && oldVal) {
    if (newVal.length < oldVal.length) {
      const index = oldVal.indexOf(removeTaskStr.value)
      data.value.taskIds = data.value.taskIds.filter((item, cindex) => cindex !== index)
    }
  }
}, {
  deep: true,
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`到期提醒-${dialogStatus}`"
    width="30%"
    :before-close="dialogClose"
    append-to-body
    :open-delay="0"
    :close-on-click-modal="false"
  >
    <!-- 选择设备 -->
    <device ref="deviceRef" @add="confirmDevice" />
    <task ref="taskRef" @add="confirmTask" />
    <el-form
      ref="dataFormRef" :model="data" :rules="rules" label-position="left" label-width="110px" class="form-container"
      size="default" @submit.prevent
    >
      <el-row :gutter="24">
        <el-col :span="24" class="grid-cell">
          <el-form-item label="提醒名称" prop="remindName" class="required">
            <el-input v-model="data.remindName" type="text" placeholder="到期提醒名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24" class="grid-cell">
          <el-form-item label="到期提醒类型" prop="remindType" class="required">
            <el-radio-group v-model="data.remindType" class="ml-4" :disabled="dialogStatus === '编辑'">
              <el-radio label="1" size="large">
                设备到期提醒
              </el-radio>
              <el-radio label="2" size="large">
                任务到期提醒
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="grid-cell">
          <el-form-item :label="`${data.remindType === '1' ? '设备提醒名称' : '任务提醒名称'}`" :prop="`${data.remindType === '1' ? 'modelIds' : 'taskIds'}`" class="required">
            <el-select
              v-if="data.remindType === '1'"
              v-model="data.equipmentExt"
              multiple
              :max-collapse-tags="10"
              placeholder="设备提醒名称"
              style="width: 100%;"
              @focus="selectDevice"
              @remove-tag="removeDevice"
            />
            <el-select
              v-if="data.remindType === '2'"
              v-model="data.taskExt"
              multiple
              :max-collapse-tags="10"
              placeholder="任务提醒名称"
              style="width: 100%;"
              @focus="selectTask"
              @remove-tag="removeTask"
            >
              <!-- <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> -->
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="grid-cell">
          <el-form-item label="提醒时间" prop="remindTime" class="required">
            <el-input-number v-model="data.remindTime" :min="0" controls-position="right" placeholder="到期前xx天" /> 天
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="dialogClose">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
::v-deep(.el-popper) {
  display: none !important;
  z-index: 10 !important;
}

::v-deep(.el-select-dropdown) {
  display: none !important;
  z-index: 10 !important;
}

.form-container {
  width: 100%;

  .full-width-input {
    width: 100%;
  }

  .dict-detail {
    padding: 10px;

    .title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
    }
  }
}
</style>
