<template>
  <view>
    <view class="top-heder">
      <view class="t-left" @click="getback()">
        <uni-icons type="left" size="18"></uni-icons>
      </view>
      <view class="t-title">
        <text>{{ title }}</text>
      </view>
      <view class="t-you"></view>
    </view>
    <view class="outer-container">
      <view class="report-form">
        <u-form @submit="onSubmit" label-width="80px">
          <u-form-item label="汇报主题" required>
            <u-input v-model="report.reportTopic" placeholder="请输入"/>
          </u-form-item>
          <u-form-item label="汇报时间">
            <view @click="isShowReportTime = true">{{ formatDateTimeToMinute(report.reportTime) }}</view>
          </u-form-item>
          <u-form-item label="汇报给">
            <u-input v-model="reportTosStr" disabled></u-input>
            <u-button type="primary" style="width: 20rpx" size="mini" @click="addRecipient">+</u-button>
          </u-form-item>
          <u-form-item label="汇报内容" required>
            <u-textarea v-model="report.reportContent" placeholder="请输入"/>
          </u-form-item>
          <u-form-item label="附件">
            <view style="display: flex; align-items: center;">
              <u-upload
                  :fileList="fileList1"
                  @afterRead="afterRead"
                  @delete="deletePic"
                  name="1"
                  multiple
                  :maxCount="10"
              ></u-upload>
            </view>
          </u-form-item>
          <u-form-item class="submit-btn-container">
            <u-button type="primary" block @click="onSubmit">保存</u-button>
          </u-form-item>
        </u-form>
      </view>
      <u-datetime-picker
          :show="isShowReportTime"
          @cancel="isShowReportTime = false"
          @confirm="selectReportTime"
          v-model="report.reportTime"
          mode="datetime"
      ></u-datetime-picker>
      <qianziyu-select
          :show="isShowReportTo"
          type="checkbox"
          name="nickname"
          :dataLists="reportToList"
          :showSearch=false
          @cancel="isShowReportTo = false"
          :checkboxData="report.reportTos"
          @submit="onReportToSubmit"
          @update:checkboxData="report.reportTos = $event"
      >
      </qianziyu-select>
    </view>
  </view>
</template>

<script>
import request from "@/utils/request";
import upload from "@/utils/upload";
import {formatDateTimeToMinute} from "@/utils/utils";
import config from "@/config";

export default {
  data() {
    return {
      report: {
        reportTopic: '',
        reportContent: '',
        reportTime: new Date(),
        reportTos: [],
        servicePackageId: "jiance",
      },
      attachments: [],
      type: 'add',
      fileList1: [],
      isShowReportTime: false,
      isShowReportTo: false,
      reportToList: [],
      reportTosStr: '',
      title: "新增汇报",
      baseImageUrl: config.baseImageUrl,
    };
  },
  async onLoad(data) {
    await this.getReportTo();  // 等待 getReportTo 执行完成
    this.type = data.type
    if (data.type === 'edit') {
      this.title = "编辑汇报"
      await this.getWorkReport(data.id)
    }
  },
  methods: {
    formatDateTimeToMinute,
    async getReportTo() {
      await request({
        url: '/work/report/queryReportTo',
        method: 'get',
        params: {
          dictType: "ins_report_role"
        }
      }).then(res => {
        this.reportToList = res.data
      })
    },
    getback() {
      uni.navigateBack({
        delta: 1, // 返回上一页
      });
    },

    /** 获取汇报对象 */
    async getWorkReport(id) {
      await request({
        url: '/work/report/get?id=' + id,
        method: 'get'
      }).then(res => {
        this.report = res.data
        // 根据 ID 数组查找对应的数据,并赋值给 report.reportTos
        this.report.reportTos = this.reportToList.filter(item => res.data.reportTos.includes(item.id));
        this.reportTosStr = this.report.reportTos.map(item => item.nickname).join(',')
        if (res.data.filePath) {
          this.fileList1 = res.data.filePath.split(',').map(item => {
            return {
              url: this.baseImageUrl + "/" + item
            }
          })
        }
      })
    },

    /** 表单提交 */
    onSubmit() {
      //校验
      const isValid = this.checkForm()
      if (!isValid) {
        return
      }
      //将文件转为字符串
      this.report.filePath = this.fileList1
          .map(item => item.url.replace(/^https?:\/\/[^/]+\/minio\//, '')) // 去除域名和 minio/
          .join(',');

      this.report.reportTos = this.report.reportTos.map(item => item.id)
      let url = '/work/report/create'
      let method = 'post'
      if (this.type === 'edit') {
        url = '/work/report/update'
        method = 'put'
      }
      request({
        url: url,
        method: method,
        data: this.report
      }).then(res => {
        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'none',
            duration: 2000
          });
          setTimeout(() => {
            // 在跳回之前刷新页面
            uni.navigateBack({
              delta: 1, // 跳回前一个页面
              success: () => {
                // 刷新当前页面数据
                uni.reLaunch({
                  url: '/pages/manage/workReport/workReport'  // 替换为你要刷新页面的路径
                });
              }
            });
          }, 2000);
        }
      })
    },
    /** 校验 */
    checkForm() {
      if (this.report.reportTos.length === 0) {
        if (!this.report.reportTopic) {
          uni.showToast({
            title: '请输入汇报主题',
            icon: 'none',
            duration: 2000
          });
          return false
        }

        uni.showToast({
          title: '请选择汇报对象',
          icon: 'none',
          duration: 2000
        });
        return false
      }

      if (!this.report.reportContent) {
        uni.showToast({
          title: '请输入汇报内容',
          icon: 'none',
          duration: 2000
        });
        return false
      }
      return true
    },
    addRecipient() {
      // Add recipient logic here
      this.isShowReportTo = true
    },
    uploadFile() {
      // Upload file logic here
    },
    onReportToSubmit(selectedData) {
      this.isShowReportTo = false
      this.report.reportTos = selectedData
      this.reportTosStr = selectedData.map(item => item.nickname).join(',')
    },
    selectReportTime(e) {
      this.report.reportTime = e.value
      this.isShowReportTime = false
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: "success",
              message: "",
              url: result,
            })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        upload({
          url: '/common/upload',
          filePath: url,
        }).then((res) => {
          setTimeout(() => {
            resolve(res.data.url);
          }, 1000);
        });
      });
    },
  }
};
</script>

<style scoped>
.outer-container {
  background-color: #f0f0f0; /* 浅灰色背景 */
  padding: 20rpx;
  min-height: 100vh; /* 保证至少占满屏幕高度 */
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* 使内容和按钮之间有间距 */
}

.report-form {
  background-color: #fff; /* 白色背景 */
  padding: 40rpx;
  border-radius: 10rpx; /* 可选,给表单加上圆角 */
//flex: 1; /* 确保表单占据剩余空间 */
}

.submit-btn-container {
//margin-top: 20rpx; /* 给保存按钮设置距离 */ //margin-bottom: 20rpx; /* 保证距离页面底部 20rpx */
}

.top-heder {
  width: 100%;
  height: 68px;
  background: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 5px 15px;
  margin-top: 2rem;
}

.t-title {
  font-size: 17px;
  font-weight: bold;
  color: #333333;
}

.t-left {
  width: 20%;
  height: 20px;
}

.t-you {
  width: 20%;
  height: 20px;
}


.t-input {
  width: 75%;
  height: 36px;
  background: #F0F0F0;
  border-radius: 50px;
  box-sizing: border-box;
  padding: 0 15px;
  display: flex;
  align-items: center;
}

.sou {
  width: 10%;
  margin-left: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.searchContent {
  display: flex;
  justify-content: center;
}

</style>