<template>
  <uni-popup ref="popup" type="bottom">
    <view class="handle-popup">
      <view class="popup-header">
        <text class="popup-title">处理祈愿</text>
        <text class="popup-close" @click="close">×</text>
      </view>

      <scroll-view scroll-y class="popup-body">
        <view class="form-item">
          <text class="label">处理结果</text>
          <textarea
            class="textarea"
            v-model="form.handlerReslut"
            placeholder="请输入处理结果"
            maxlength="500"
            :auto-height="true"
          />
          <text class="count">{{ (form.handlerReslut || '').length }}/500</text>
        </view>

        <view class="form-item">
          <text class="label">处理图片</text>
          <view class="upload-section">
            <view class="upload-list">
              <view
                class="upload-item"
                v-for="(image, index) in images"
                :key="index"
              >
                <image :src="HTTP_ADMIN_URL + '/' + (image.url || image.attDir || image.filePath || '')" mode="aspectFill"></image>
                <text class="delete-btn" @click="deleteImage(index)">×</text>
              </view>
              <view class="upload-btn" @click="chooseImage" v-if="images.length < 9">
                <text class="iconfont icon-tianjia"></text>
                <text>添加图片</text>
              </view>
            </view>
            <text class="hint">最多上传9张图片</text>
          </view>
        </view>
      </scroll-view>

      <view class="popup-footer">
        <view class="submit-btn" @click="handleSubmit">提交处理</view>
      </view>
    </view>
  </uni-popup>
</template>

<script>
import { HTTP_ADMIN_URL } from '@/config/app';
import request from '@/utils/request.js';

export default {
  data() {
    return {
      HTTP_ADMIN_URL,
      currentItem: null,
      form: {
        handlerReslut: ''
      },
      images: []
    };
  },
  methods: {
    open(item) {
      this.currentItem = item;
      this.form.handlerReslut = item.handlerReslut || '';
      this.images = item.afterProcessFiles && item.afterProcessFiles.length ? [...item.afterProcessFiles] : [];
      this.$refs.popup.open();
    },
    close() {
      this.$refs.popup.close();
    },
    chooseImage() {
      // #ifndef MP-WEIXIN
      uni.chooseImage({
        count: 9 - this.images.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadImages(res.tempFilePaths);
        }
      });
      // #endif
      // #ifdef MP-WEIXIN
      uni.chooseMedia({
        count: 9 - this.images.length,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        sizeType: ['compressed'],
        success: (res) => {
          const tempFilePaths = res.tempFiles.map(file => file.tempFilePath);
          this.uploadImages(tempFilePaths);
        }
      });
      // #endif
    },
    async uploadImages(filePaths) {
      for (let i = 0; i < filePaths.length; i++) {
        try {
          uni.showLoading({ title: '上传中...', mask: true });
          const result = await request.uploadFile(filePaths[i], 'multipart', {}, {
            params: { model: 'app-wish', pid: 10 }
          });
          this.images.push(result);
        } catch (e) {
          console.error('上传图片失败:', e);
          uni.showToast({ title: '上传失败', icon: 'none' });
        } finally {
          uni.hideLoading();
        }
      }
    },
    deleteImage(index) {
      this.images.splice(index, 1);
    },
    getCurrentTime() {
      const now = new Date();
      return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    },
    normalizeFile(file) {
      const attDir = file.url || file.attDir || file.filePath || '';
      return {
        attId: (file.id || file.attId || '') + '',
        name: file.fileName || file.name,
        attDir,
        attSize: file.fileSize || file.attSize,
        attType: file.type || file.attType,
        fileName: file.fileName || file.name,
        filePath: attDir,
        url: attDir,
        originalFileName: file.fileName || file.originalFileName || file.name
      };
    },
    handleSubmit() {
      const result = (this.form.handlerReslut || '').trim();
      if (!result) {
        uni.showToast({ title: '请输入处理结果', icon: 'none' });
        return;
      }
      const afterProcessFiles = this.images.map(file => this.normalizeFile(file));
      const payload = {
        ...this.currentItem,
        handlerReslut: result,
        handlerDate: this.getCurrentTime(),
        afterProcessFiles,
        status: '3',
      };
      this.$emit('submit', payload);
    }
  }
};
</script>

<style lang="scss">
.handle-popup {
  width: 100%;
  max-height: 80vh;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  display: flex;
  flex-direction: column;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    flex-shrink: 0;

    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .popup-close {
      font-size: 50rpx;
      color: #999;
      line-height: 1;
    }
  }

  .popup-body {
    flex: 1;
    padding: 30rpx;
    max-height: 55vh;

    .form-item {
      margin-bottom: 30rpx;

      .label {
        display: block;
        font-size: 28rpx;
        color: #374151;
        margin-bottom: 12rpx;
        font-weight: 500;
      }

      .textarea {
        width: 100%;
        min-height: 160rpx;
        background: #f9fafb;
        border-radius: 12rpx;
        padding: 20rpx;
        font-size: 28rpx;
        box-sizing: border-box;
        line-height: 1.6;
      }

      .count {
        display: block;
        margin-top: 10rpx;
        text-align: right;
        font-size: 22rpx;
        color: #999;
      }

      .upload-section {
        .upload-list {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;

          .upload-item {
            width: 180rpx;
            height: 180rpx;
            position: relative;
            border-radius: 12rpx;
            overflow: hidden;

            image {
              width: 100%;
              height: 100%;
            }

            .delete-btn {
              position: absolute;
              top: 10rpx;
              right: 10rpx;
              width: 40rpx;
              height: 40rpx;
              background: rgba(0, 0, 0, 0.6);
              color: #fff;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 32rpx;
            }
          }

          .upload-btn {
            width: 180rpx;
            height: 180rpx;
            border: 2rpx dashed #d9d9d9;
            border-radius: 12rpx;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: #fafafa;

            .iconfont {
              font-size: 48rpx;
              color: #bfbfbf;
              margin-bottom: 8rpx;
            }

            text {
              font-size: 24rpx;
              color: #999;
            }
          }
        }

        .hint {
          display: block;
          margin-top: 16rpx;
          font-size: 22rpx;
          color: #999;
        }
      }
    }
  }

  .popup-footer {
    padding: 20rpx 30rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    border-top: 1rpx solid #f0f0f0;
    flex-shrink: 0;

    .submit-btn {
      height: 88rpx;
      background: #3b82f6;
      color: #fff;
      border-radius: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 30rpx;
      font-weight: 600;
    }
  }
}
</style>
