<template>
  <div class="facilities-dialog-container">
    <van-popup
      v-model:show="state.dialog.isShowDialog"
      position="bottom"
      round
      :style="{ height: '90%' }"
      close-on-popstate
    >
      <div class="vant-dialog">
        <header class="vant-dialog__header">
          <h4>{{ state.dialog.title }}</h4>
        </header>
        <main class="vant-dialog__body">
          <section class="section">
            <van-cell-group inset>
              <h5 class="section__title">申请信息</h5>
              <van-cell
                title="入室申请名称"
                :value="`${state.oldForm.userName}的${state.oldForm.platformName}的入室申请`"
              />
              <van-cell
                title="申请平台"
                :value="state.oldForm.platformName"
              />
              <van-cell
                title="入室周期"
                :title-style="{ flex: '0 0 80px', maxWidth: '80px' }"
                :value="`${
                  state.oldForm?.startTime ? formatDate(new Date(state.oldForm?.startTime), 'YYYY-mm-dd') : ''
                } ~ ${state.oldForm?.endTime ? formatDate(new Date(state.oldForm?.endTime), 'YYYY-mm-dd') : ''}`"
              />
              <van-cell
                title="预约房间"
                :value="state.oldForm.resName"
              />
            </van-cell-group>
          </section>

          <section class="section">
            <van-cell-group inset>
              <h5 class="section__title">预约信息</h5>
              <van-field
                label="开始时间"
                v-model="state.form.startTime"
                readonly
                input-align="right"
              />
              <van-field
                label="结束时间"
                v-model="state.form.endTime"
                readonly
                input-align="right"
              />
              <van-field
                label="预约时长"
                :model-value="state.form.duration + '分钟'"
                readonly
                input-align="right"
              />
              <van-field
                v-model="state.form.remark"
                label="备注"
                type="textarea"
                rows="3"
                maxlength="200"
                show-word-limit
                placeholder="请输入备注"
              />
            </van-cell-group>
          </section>
        </main>
        <van-action-bar
          placeholder
          safe-area-inset-bottom
        >
          <van-action-bar-button
            text="取消"
            type="warning"
            @click="onCancel"
          />
          <van-action-bar-button
            type="primary"
            color="#2c78ff"
            :text="state.dialog.submitTxt || '提交'"
            :loading="state.dialog.submitting"
            :disabled="state.dialog.submitting"
            @click="onSubmit('20')"
          />
        </van-action-bar>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts" name="systemProDialog">
  import { nextTick, reactive, ref } from 'vue'
  import to from 'await-to-js'
  import moment from 'moment/moment'
  import { storeToRefs } from 'pinia'
  import { showToast } from 'vant'

  import { useSystemApi } from '/@/api/platform/system'
  import { deepClone } from '/@/utils/other'
  import { useAppointmentApi } from '/@/api/platform/home/appointment'
  import { useUserInfo } from '/@/stores/userInfo'
  import { formatDate } from '/@/utils/formatTime'
  import { useCellAssignApi } from '/@/api/platform/home/assign'

  // 定义子组件向父组件传值/事件
  const emit = defineEmits(['refresh'])

  // 定义变量内容
  const Api = useAppointmentApi()
  const assignApi = useCellAssignApi()
  const systemApi = useSystemApi()
  const stores = useUserInfo()
  const { userInfos } = storeToRefs(stores)
  const state = reactive({
    form: {
      id: 0,
      assignId: 0,
      appointId: 0,
      userId: 0,
      userName: '',
      userDeptId: null,
      userDeptName: '',
      userContact: '',
      startTime: null,
      endTime: null,
      remark: '',
      duration: 0,
    },
    oldForm: {
      id: 0,
      appointId: 0,
      mainId: 0,
      platformId: 0,
      platformName: '',
      resId: 0,
      resLocation: '',
      resName: '',
      userId: 0,
      userName: '',
      assignStatus: '',
      startTime: '',
      endTime: '',
      oldStartTime: '',
      oldEndTime: '',
      isConfirm: '',
      location: 0,
      outApplyTime: '',
      outStatus: 0,
      outTime: null,
    },
    dialog: {
      isShowDialog: false,
      type: '',
      title: '',
      submitTxt: '',
      submitting: false,
    },
  })

  const belongOrgOption = ref<DeptTreeType[]>([])
  const userList = ref<any[]>([]) //用户列表
  const getDicts = async () => {
    await Promise.all([systemApi.getDeptTree(), systemApi.getUserList({ noPage: true })]).then(([dept, user]) => {
      belongOrgOption.value = dept?.data || []
      userList.value = user?.data.list || []
    })
  }
  // 打开弹窗
  const openDialog = async (type: string, row: any) => {
    await getDicts()
    state.dialog.type = type
    state.dialog.title = '使用预约'
    if (type == 'add') {
      state.form = {
        id: row?.id,
        assignId: row?.id,
        appointId: row?.appointId,
        userId: userInfos.value.id,
        userName: userInfos.value.nickName,
        userDeptId: userInfos.value.deptId,
        userDeptName: userInfos.value.deptName,
        userContact: userInfos.value.phone,
        startTime: row?.startTime,
        endTime: row?.endTime,
        remark: '',
        duration: 0,
      }
      const [err, res]: ToResponse = await to(assignApi.getDetail({ id: row?.id }))
      if (err) return
      state.oldForm = res?.data || {}

      // 计算startTime和endTime的分钟差
      const diff = moment(state.form.endTime).diff(moment(state.form.startTime), 'minutes')
      state.form.duration = diff
    } else {
      const [err, res]: ToResponse = await to(Api.getDetail({ id: row?.id }))
      if (err) return
      state.form = res?.data || {}
    }

    state.dialog.submitTxt = '提 交'
    state.dialog.isShowDialog = true
    // 清空表单，此项需加表单验证才能使用
    await nextTick()
  }

  // 关闭弹窗
  const closeDialog = () => {
    state.dialog.isShowDialog = false
  }

  const onCancel = () => {
    closeDialog()
  }

  // 提交
  const onSubmit = async (type: string) => {
    if (state.dialog.submitting) return
    state.dialog.submitting = true
    // 基础必填校验（开始/结束时间）
    if (!state.form.startTime || !state.form.endTime) {
      showToast('开始时间和结束时间不能为空')
      state.dialog.submitting = false
      return
    }
    const params: any = deepClone(state.form)
    params.isTemporary = type
    const post = state.dialog.type == 'add' ? Api.create : Api.updateById
    const [err]: ToResponse = await to(post(params))
    if (err) {
      state.dialog.submitting = false
      return
    }
    showToast('操作成功')
    closeDialog()
    emit('refresh')
    state.dialog.submitting = false
  }
  // 暴露变量
  defineExpose({
    openDialog,
  })
</script>
<style lang="scss" scoped>
  .vant-dialog {
    display: flex;
    flex-direction: column;
    height: 100%;
    background-color: #f7f8fa;
    &__header {
      padding: 12px 16px;
      border-bottom: 1px solid #f0f0f0;
      h4 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }
    &__body {
      flex: 1;
      overflow-y: auto;
      padding: 12px 0 60px;
    }
  }
  .section {
    margin-bottom: 12px;
    &__title {
      margin: 4px 10px 6px;
      font-size: 13px;
      color: #969799;
    }
  }
  :deep(.disUoloadSty .el-upload--picture-card) {
    display: none; /* 上传按钮隐藏 */
  }
  .avatar-uploader {
    :deep(.el-upload) {
      width: 100%;
      height: 100%;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      &:hover {
        border-color: var(--el-color-primary);
      }
    }
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
</style>
