<script setup lang="ts">
import dayjs from 'dayjs'
// import { storeToRefs } from 'pinia'
import { onMounted, reactive, ref, watch } from 'vue'
import { useToast } from 'wot-design-uni'
import { submitIssue } from '@/api/schedule/issue'
import { getTags } from '@/api/system/tags'
import { getAllUsers } from '@/api/system/users'
import useUpload from '@/hooks/useUpload'
// import { useUserStore } from '@/store'
// import calendar from '@/utils/calendar.vue'

const props = defineProps({
  taskId: {
    type: Number,
    default: 0,
  },
  stationId: {
    type: Number,
    default: 0,
  },
  checkItemId: {
    type: Number,
    default: 0,
  },
  anomalyData: {
    type: Object,
    default: () => ({}),
  },
})
const emit = defineEmits(['update:anomalyShow', 'anomaly-submitted'])
console.log(props.stationId)
const tags = ref<any[]>([])
const users = ref<any[]>([])
// const userStore = useUserStore()
// const { userInfo } = storeToRefs(userStore)

async function getUserList() {
  console.log('调用getAllUsers时的stationId:', props.stationId)
  const res: any = await getAllUsers({
    pageNum: 10000,
    stationId: props.stationId,
  })
  if (res.code === 200) {
    users.value = res.data.map((item: any) => ({
      label: item.nickName,
      value: item.userId,
    }))
  }
}

async function getTagsList(name: string = '') {
  const params: any = {
    pageNum: 10000,
  }
  if (name) {
    params.tagName = name
  }
  const res: any = await getTags(params)
  if (res.code === 200) {
    tags.value = res.rows.map((item: any) => ({
      label: item.tagName,
      value: item.id,
    }))
  }
}

const { success: showSuccess } = useToast()

const model = reactive<{
  isTransferTask: string
  problemDescription: string
  handlingSuggestion: string
  deadline: string
  executorId: string
  ccTo: string[]
  handlingMeasure: string
  handlingPhoto: string[]
  problemPhoto: any
  tags: string[]
  correlationTaskId: string
}>({
  isTransferTask: '1',
  problemDescription: '',
  handlingSuggestion: '',
  deadline: '',
  executorId: '',
  ccTo: [],
  handlingMeasure: '',
  handlingPhoto: [],
  problemPhoto: [],
  tags: [],
  correlationTaskId: '',
})

// 更新 model 数据
function updateModelData(data: any) {
  if (!data)
    return

  model.isTransferTask = data.isTransferTask?.toString() || '1'
  model.problemDescription = data.problemDescription || ''
  model.handlingSuggestion = data.handlingSuggestion || ''
  model.deadline = data.deadline || ''
  model.executorId = data.executorId ? [Number(data.executorId)] : []
  model.ccTo = data.ccTo ? data.ccTo.split(',').map((item: string) => Number(item.trim())) : []
  model.problemPhoto = data.problemPhoto || []
  model.tags = data.tags ? data.tags.split(',').map((item: string) => Number(item.trim())) : []
  model.correlationTaskId = data.correlationTaskId?.toString() || ''
}

const form = ref()
const loading = ref(false)

// 上传问题照片
const uploadProblemPhoto: any = (file, formData, options) => {
  const { customUpload } = useUpload({
    fileType: 'image',
  })
  return customUpload(file, formData, options)
}

// 删除问题照片
function deleteProblemPhoto(index: number) {
  model.problemPhoto.splice(index, 1)
}

function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        // 准备提交数据
        const submitData = {
          isTransferTask: Number.parseInt(model.isTransferTask),
          problemDescription: model.problemDescription,
          handlingSuggestion: model.handlingSuggestion,
          deadline: dayjs(model.deadline).format('YYYY-MM-DD 23:59:59'),
          executorId: model.executorId?.[0] || '',
          ccTo: model?.ccTo?.join(',') || '',
          tags: model?.tags?.join(',') || '',
          problemPhoto: (model.problemPhoto?.map((item: any) => item.name) || []).join(','),
          correlationTaskId: props.taskId,
          checkItemId: props.checkItemId,
          // 其他字段根据实际情况处理
        }

        console.log('提交数据:', submitData)

        // 开始提交，显示 loading
        loading.value = true

        submitIssue(submitData)
          .then((res) => {
            // 提交成功后向父组件传递数据
            emit('anomaly-submitted', { checkItemId: props.checkItemId, data: {
              ...submitData,
              problemPhoto: model.problemPhoto,
            } })

            console.log(res, 'res')
            // 重置表单数据
            model.isTransferTask = '1'
            model.problemDescription = ''
            model.handlingSuggestion = ''
            model.deadline = ''
            model.executorId = ''
            model.ccTo = []
            model.handlingMeasure = ''
            model.handlingPhoto = []
            model.problemPhoto = []
            model.tags = []
            model.correlationTaskId = ''
          })
          .catch((error) => {
            console.log(error, 'error')
          })
          .finally(() => {
            // 提交完成，隐藏 loading
            loading.value = false
            emit('update:anomalyShow', false)
          })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

onMounted(() => {
  getTagsList()
  getUserList()
})

// 监听stationId变化，当stationId从0变为实际值时重新获取用户列表
watch(() => props.stationId, (newStationId) => {
  console.log('stationId变化:', newStationId)
  if (newStationId > 0) {
    getUserList()
  }
}, { immediate: false })

defineExpose({
  updateModelData,
})
</script>

<template>
  <view>
    <view class="popup-content">
      <view class="content-header">
        <text style="font-size: 34rpx; font-weight: 500; color: #464c51">
          异常情况
        </text>
      </view>
      <view class="content-main">
        <wd-form ref="form" :model="model">
          <view style="display: flex; flex-direction: column; gap: 40rpx; padding-bottom: 100rpx;">
            <view>
              <view style="font-size: 32rpx; font-weight: 500; color: #31373d">
                是否转任务
              </view>
              <view
                style="
                    font-size: 28rpx;
                    font-weight: 400;
                    color: #4e5969;
                    margin-bottom: 20rpx;
                  "
              >
                转任务后会出现在执行人的任务日程视图中
              </view>
              <wd-radio-group v-model="model.isTransferTask" shape="dot" inline>
                <view style="display: flex; gap: 260rpx">
                  <wd-radio value="1">
                    是
                  </wd-radio>
                  <wd-radio value="0">
                    否
                  </wd-radio>
                </view>
              </wd-radio-group>
            </view>
            <wd-input
              v-model="model.problemDescription"
              label="问题描述"
              label-width="100%"
              prop="problemDescription"
              clearable
              placeholder="请输入"
              :rules="[{ required: true, message: '请填写问题描述' }]"
              custom-class="custom-vertical-input"
            />
            <view class="custom-vertical-select">
              <view
                style="
                    margin-bottom: 10rpx;
                    font-size: 28rpx;
                    font-weight: 500;
                    color: #333;
                  "
              >
                标签
              </view>
              <wd-select-picker
                v-model="model.tags" :columns="tags" filterable
                :max="1"
                placeholder="请选择"
              />
            </view>
            <wd-input
              v-model="model.handlingSuggestion"
              label="处理建议"
              label-width="100%"
              prop="handlingSuggestion"
              clearable
              placeholder="请输入"
              custom-class="custom-vertical-input"
            />
            <view class="custom-vertical-select">
              <view
                style="
                    margin-bottom: 10rpx;
                    font-size: 28rpx;
                    font-weight: 500;
                    color: #333;
                  "
              >
                <text style="color: red; margin-right: 4rpx; font-size: 28rpx;">* </text>截止时间
              </view>
              <wd-datetime-picker
                v-model="model.deadline"
                type="date"
                use-second
                :min-date="new Date().getTime()"
                :max-date="new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).getTime()"
                prop="deadline"
                :rules="[{ required: true, message: '请选择截止时间' }]"
              />
            </view>
            <view>
              <view
                style="
                    margin-bottom: 10rpx;
                    font-size: 28rpx;
                    font-weight: 500;
                    color: #333;
                  "
              >
                问题照片
              </view>
              <view>
                <wd-upload
                  v-model:file-list="model.problemPhoto"
                  image-mode="aspectFill"
                  :upload-method="uploadProblemPhoto"
                  @delete="deleteProblemPhoto"
                />
              </view>
            </view>
            <view class="custom-vertical-select">
              <view
                style="
                    margin-bottom: 10rpx;
                    font-size: 28rpx;
                    font-weight: 500;
                    color: #333;
                  "
              >
                <text style="color: red; margin-right: 4rpx; font-size: 28rpx;">* </text>执行人
              </view>
              <wd-select-picker
                v-model="model.executorId" :columns="users" filterable
                placeholder="请选择"
                prop="executorId"
                :max="1"
                :rules="[{ required: true, message: '请选择执行人' }]"
              />
            </view>
            <view class="custom-vertical-select">
              <view
                style="
                    margin-bottom: 10rpx;
                    font-size: 28rpx;
                    font-weight: 500;
                    color: #333;
                  "
              >
                抄送人
              </view>
              <wd-select-picker
                v-model="model.ccTo" :columns="users" filterable
                placeholder="请选择"
              />
            </view>
          </view>
        </wd-form>
      </view>
      <view class="footer">
        <button class="btn" :disabled="loading" @click="handleSubmit">
          <wd-loading v-if="loading" size="20px" color="#ffffff" />
          <text v-else>提 交</text>
        </button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.custom-txt {
  width: 400rpx;
  height: 400rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 32rpx;
}
.popup-content {
  min-height: 500rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 30rpx;
  // padding: 0 30rpx 30rpx 30rpx;
  box-sizing: border-box;
  overflow-y: auto;
  .content-header {
    // height: 80rpx;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 30rpx;
    // position: sticky;
    // top: 50rpx;
    // background-color: #fff;
    // border: 1px solid red;
    // z-index: 50;
    text {
      font-size: 32rpx;
      font-weight: 600;
    }
  }
  .content-main {
    width: 100%;
    .wd-select-picker,
    .wd-datetime-picker {
      width: 100%;
      & .wd-cell {
        padding: 0;
      }
      & .wd-cell__right {
        width: 100%;
        & .wd-cell__value {
          width: 100%;
          & .wd-select-picker__input,
          & .wd-datetime-picker__input {
            width: 100%;
            height: 70rpx;
            border: 1px solid #e5e5e5;
            border-radius: 8rpx;
            padding: 0 20rpx;
            font-size: 28rpx;
          }
        }
      }
    }
    .custom-vertical-select {
      margin-bottom: 30rpx;
    }
    .wd-input {
      // margin-bottom: 30rpx;
      padding: 0px;
      &.custom-vertical-input {
        display: flex;
        flex-direction: column;
        gap: 10rpx;
        margin-bottom: 30rpx;

        .wd-input__label {
          width: 100% !important;
          margin-bottom: 10rpx;
          font-size: 28rpx;
          font-weight: 500;
          color: #333;
        }

        .wd-input__body {
          width: 100%;
          position: relative;
        }

        /* 使用Vue 3深度选择器确保样式能正确应用到输入框 */
        :deep(.wd-input__inner) {
          width: 20rem !important;
          height: 70rpx !important;
          border: 1px solid #e5e5e5 !important;
          border-radius: 8rpx !important;
          padding: 0 60rpx 0 20rpx !important;
          font-size: 28rpx !important;
        }

        /* 确保图标容器在输入框内部 */
        :deep(.wd-input__suffix) {
          position: absolute;
          right: 20rpx;
          top: 50%;
          transform: translateY(-50%);
          z-index: 1;
        }
      }
    }
  }
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 30rpx;
  padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  background-color: white;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 10;
  .btn {
    width: 100%;
    height: 80rpx;
    background-color: #215acd;
    color: white;
    font-size: 32rpx;
    border-radius: 12rpx;
    font-weight: 400;
    border: none;
    outline: none;
  }
}
</style>
