<template>
  <view class="app-container">
    <uni-forms ref="sendEmailFormRef" :model="sendEmailForm" label-width="80" label-position="top">
      <uni-forms-item label="发件人" name="emailAccountId" required>
        <uni-data-select v-model="sendEmailForm.emailAccountId" :localdata="senderOptions" placeholder="请选择发件人邮箱账号" />
      </uni-forms-item>
      <uni-forms-item label="选择联系人" name="toList" required>
        <input class="uni-input" v-model="contactSearch" placeholder="搜索公司名/邮箱" style="margin-bottom: 12rpx;" @input="onContactSearchInput" />
        <view class="checkbox-scroll-container">
          <uni-data-checkbox multiple v-model="sendEmailForm.toList" :localdata="contactOptions" />
        </view>
      </uni-forms-item>
      <uni-forms-item label="邮件主题" name="subject" required>
        <input class="uni-input" v-model="sendEmailForm.subject" placeholder="请输入邮件主题" />
      </uni-forms-item>
      <uni-forms-item label="邮件正文" name="content" required>
        <Quill v-model="sendEmailForm.content" :min-height="192" />
      </uni-forms-item>
      <view class="form-actions">
        <button type="primary" :loading="sendEmailLoading" @click="submitSendEmail" :disabled="sendEmailLoading">
          {{ sendEmailLoading ? '发送中...' : '发送' }}
        </button>
        <button @click="resetSendEmailForm" :disabled="sendEmailLoading">重置</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { listFurnitureTable } from "@/api/oa/contact";
import { listEmailAccount, sendEmail } from "@/api/oa/emailAccount";
import { listByIds } from '@/api/oa/oss';

export default {
  name: "SalesEmailPage",
  data() {
    return {
      loading: true,
      furnitureTableList: [],
      emailAccountList: [],
      sendEmailLoading: false,
      sendEmailForm: {
        emailAccountId: 0,
        toList: [],
        subject: '',
        content: '',
        attachments: []
      },
      contactSearch: '',
      contactSearchTimer: null,
    };
  },
  computed: {
    contactOptions() {
      // 只显示有邮箱的联系人
      return this.furnitureTableList.filter(item => item.email).map(item => ({
        text: `${item.companyName}
				（${item.email}）
				${item.emailSendCount}->${item.receiveCount}
				${item.lastEmailSendTime ? '--' + item.lastEmailSendTime : ''}`,
        value: item.furnitureId,
        companyName: item.companyName,
        email: item.email
      }));
    },
    senderOptions() {
      return this.emailAccountList.map(item => ({
        text: item.email,
        value: item.emailId
      }));
    }
  },
  created() {
    this.getList();
    this.getEmailAccountList();
  },
  methods: {
    getList(keyword = '') {
      this.loading = true;
      const params = { pageNum: 1, pageSize: 100, qualityFilter: true };
      if (keyword) {
        params.companyName = keyword;
      }
      listFurnitureTable(params).then(response => {
        this.furnitureTableList = response.rows || [];
        this.loading = false;
      });
    },
    onContactSearchInput(e) {
      // 远程搜索防抖
      if (this.contactSearchTimer) clearTimeout(this.contactSearchTimer);
      this.contactSearchTimer = setTimeout(() => {
        this.getList(this.contactSearch.trim());
      }, 400);
    },
    getEmailAccountList() {
      listEmailAccount({ pageSize: 100 }).then(response => {
        this.emailAccountList = response.rows || [];
      });
    },
    // onSenderChange 已不需要
    resetSendEmailForm() {
      this.sendEmailForm = {
        emailAccountId: 0,
        toList: [],
        subject: '',
        content: '',
        attachments: []
      };
    },
    async submitSendEmail() {
      // 简单校验
      if (!this.sendEmailForm.emailAccountId && this.emailAccountList.length) {
        uni.showToast({ title: '请选择发件人', icon: 'none' });
        return;
      }
      if (!this.sendEmailForm.toList.length) {
        uni.showToast({ title: '请选择联系人邮箱', icon: 'none' });
        return;
      }
      if (!this.sendEmailForm.subject) {
        uni.showToast({ title: '请输入邮件主题', icon: 'none' });
        return;
      }
      if (!this.sendEmailForm.content) {
        uni.showToast({ title: '请输入邮件正文', icon: 'none' });
        return;
      }
      this.sendEmailLoading = true;
      let attachmentPaths = [];
      if (this.sendEmailForm.attachments && this.sendEmailForm.attachments.length > 0) {
        try {
          const res = await listByIds(this.sendEmailForm.attachments);
          attachmentPaths = (res.data || []).map(item => item.url);
        } catch (e) {
          uni.showToast({ title: '附件获取失败', icon: 'none' });
          this.sendEmailLoading = false;
          return;
        }
      }
      const sendData = {
        emailAccountId: this.sendEmailForm.emailAccountId,
        toList: this.sendEmailForm.toList.join(','),
        subject: this.sendEmailForm.subject,
        content: this.sendEmailForm.content,
        contentType: 'html',
				furnitureIds: this.sendEmailForm.toList.join(','),
        attachments: attachmentPaths
      };
      uni.showLoading({ title: '正在发送...' });
      console.log('发送邮件数据:', sendData);
      sendEmail(sendData).then(response => {
        uni.showToast({ title: response.msg || '邮件发送成功！', icon: 'success' });
        this.resetSendEmailForm();
      }).catch((error) => {
        console.error('邮件发送失败:', error);
        uni.showToast({ title: '邮件发送失败，请检查网络连接或稍后重试', icon: 'none' });
      }).finally(() => {
        this.sendEmailLoading = false;
					uni.hideLoading();
      });
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 24rpx;
}
.form-section {
  /* 已由uni-forms接管布局 */
}
.form-item {
  /* 已由uni-forms接管布局 */
}
.form-label {
  /* 已由uni-forms接管布局 */
}
.picker-value {
  /* 已由uni-forms接管布局 */
}
.form-actions {
  display: flex;
  gap: 24rpx;
}
.list-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.04);
}
  .checkbox-scroll-container {
    max-height: 300rpx;
    overflow-y: auto;
    border: 1rpx solid #eee;
    border-radius: 8rpx;
    padding: 12rpx;
    background: #fafbfc;
  }
</style>