<!-- 编辑日程 -->
<script setup lang="ts" name="EditSchedule">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import { delSchedule, editSchedule, getCalendarList } from '@/api/eqpt/dashboard/index'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
const emits = defineEmits(['editScheduleSuccess'])
const user = useUserStore()// 用户信息
const dialogVisible = ref(false)// 弹窗显示
const ruleFormRef = ref<FormInstance>() // from组件
const rules = ref<FormRules>({
  date: [{ required: true, message: '日期必填', trigger: ['blur', 'change'] }],
  markContent: [{ required: true, message: '日程必填', trigger: ['blur', 'change'] }],
}) // 表单验证规则
const form = ref({
  date: '', // 日期
  markContent: '',
})
const userInfo = ref({
  createCompanyId: '',
  createDeptId: user.deptId,
  createUserId: user.id,
})
const list = ref([{
  markContent: '', // 日程
  markDate: '',
  createCompanyId: '',
  createDeptId: '',
  createTime: '',
  createUserId: '',
  id: '',
  updateTime: '',
}]) // 日程列表
const type = ref('add') // 新增add，编辑edit
// 重置
const reset = () => {
  form.value.date = ''
  form.value.markContent = ''
  list.value = [{
    markContent: '', // 日程
    markDate: '',
    createCompanyId: '',
    createDeptId: '',
    createTime: '',
    createUserId: '',
    id: '',
    updateTime: '',
  }]
}
// 点击取消
const cancle = () => {
  dialogVisible.value = false
  reset()
}

// 点击确定
const clickConfirm = async (formEl: FormInstance | undefined) => {
  // 去掉空的日程
  // const resultArr = list.value.filter(item => item.markContent)
  // if (!resultArr.length) {
  //   ElMessage.warning('要求至少有一个日程')
  //   return false
  // }
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      const param = { ...list.value[0], ...userInfo.value, markDate: form.value.date }
      param.markContent = form.value.markContent
      if (type.value === 'add') {
        param.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        editSchedule(param).then((res) => {
          ElMessage.success('设置成功')
          dialogVisible.value = false
          emits('editScheduleSuccess')
          reset()
        })
      }
      if (type.value === 'edit') {
        param.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
        editSchedule(param).then((res) => {
          ElMessage.success('设置成功')
          dialogVisible.value = false
          emits('editScheduleSuccess')
          reset()
        })
      }
    }
  })
}

// 点击增加
const clickAdd = () => {
  if (list.value[list.value.length - 1].scheduleMatters === '') {
    ElMessage.warning('请完善上一条日程')
    return false
  }
  list.value.push({
    scheduleMatters: '',
    id: '',
  })
}
// 点击减少
const clickReduce = (index: number) => {
  list.value.splice(index, 1)
}

// 获取日程列表
const fetchCalendarList = async (date: string) => {
  const user = await getUserDept()
  const companyId = user.data.id
  userInfo.value.createCompanyId = user.data.id
  const params = {
    companyId,
    startDate: `${form.value.date}`,
    endDate: `${form.value.date}`,
  }
  getCalendarList(params).then((res) => {
    const response = res.data
    if (response.length) { // 选择的日期有日程
      // for (const key in response) {
      type.value = 'edit'
      // console.log(response[key])
      list.value = response[0]
      form.value.markContent = response[0].markContent
      // }
    }
    else { // 选择的日期没有日程
      type.value = 'add'
      list.value = [{
        markContent: '', // 日程
        markDate: '',
        createCompanyId: '',
        createDeptId: '',
        createTime: '',
        createUserId: '',
        id: '',
        updateTime: '',
      }]
    }
  })
}

// 弹窗初始化
const initDialog = (time: string) => {
  dialogVisible.value = true
  form.value.date = time
}
// 删除所有日程
const delAll = () => {
  ElMessageBox.confirm(
    '确认删除吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      delSchedule({ id: list.value[0].id }).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        cancle()
      })
    })
}
watch(() => form.value.date, (newVal) => {
  const date = dayjs(new Date(newVal)).format('YYYY-MM')
  fetchCalendarList(newVal)
})
defineExpose({ initDialog })
</script>

<template>
  <el-dialog v-model="dialogVisible" class="edit-schedule" title="编辑日程" width="35%" @close="cancle">
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-position="right" label-width="110px">
      <el-form-item label="日期" prop="date">
        <el-date-picker
          v-model="form.date"
          type="date"
          placeholder="请选择日期"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          style="width: 100%;"
        />
      </el-form-item>
      <el-form-item label="日程" prop="markContent">
        <el-input
          v-model="form.markContent"
          type="textarea"
          autosize
          placeholder="请输入日程"
          style="width: 100%;"
        />
      </el-form-item>
    </el-form>
    <!-- <ul> -->
    <!-- <li v-for="(item, index) in list" :key="index" class="li-item">
        <el-input
          v-model="item.markContent"
          type="textarea"
          autosize
          placeholder="请输入日程"
          style="width: 100%;"
        /> -->
    <!-- <div class="icon-area">
          <el-icon v-if="index === list.length - 1" name="icon-add-circle" class="title-icon" @click="clickAdd">
            <svg-icon name="icon-add-circle" />
          </el-icon>
          <el-icon v-if="index !== 0" name="icon-reduce-circle" class="title-icon reduce-icon" @click="clickReduce(index)">
            <svg-icon name="icon-reduce-circle" />
          </el-icon>
        </div> -->
    <!-- </li> -->
    <!-- </ul> -->
    <template #footer>
      <el-button type="primary" @click="clickConfirm(ruleFormRef)">
        确定
      </el-button>
      <el-button @click="cancle">
        取消
      </el-button>
      <!-- <el-button type="danger" @click="delAll">
        删除所有日程
      </el-button> -->
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.edit-schedule {
  .title-icon {
    width: 18px;
    height: 18px;
    font-size: 18px;
    line-height: 16px;
    color: #3d7eff;
    margin-right: 5px;
    cursor: pointer;
    // float: right;
  }

  .li-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 70px;
    margin-bottom: 10px;
  }

  .icon-area {
    display: flex;
    // justify-content: space-between;
    // align-items: center;
  }

  .reduce-icon {
    color: #ea5a32;
  }
}
</style>

