<template>
  <div class="operation">
    <Header :appHide="true">
      <template slot="right">
        <div v-if="type == 'update'" @click="onDel">删除</div>
      </template>
    </Header>

    <van-cell-group class="cellGroup">
      <van-field
        label="发送群组"
        required
        input-align="right"
        label-class="labelClass"
        readonly
        placeholder="请选择发送群组"
        is-link
        @click="groupStatus = true"
      >
        <template #input>
          <div class="class" v-if="selectIds.length > 0">
            {{ selectIds.length }}个群组
            <img src="./images/icon_arrow.png" />
          </div>
        </template>
      </van-field>
      <van-field label="发送方式" input-align="right" required>
        <template #input>
          <van-radio-group v-model="form.sendType" direction="horizontal">
            <van-radio name="NOW">即时发送</van-radio>
            <van-radio name="TIMING">定时发送</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field
        v-if="form.sendType == 'TIMING'"
        label="发送时间"
        required
        input-align="right"
        readonly
        is-link
        v-model="form.sendTime"
        placeholder="请选择发送时间"
        @click="timerStatus = true"
      ></van-field>
    </van-cell-group>

    <van-cell-group class="cellGroup">
      <div
        class="van-cell--required"
        style="padding: 10px 16px 0; color: #646566; font-size: 14px"
      >
        发送内容
      </div>
      <van-field
        type="textarea"
        row="2"
        placeholder="请输入发送内容"
        :border="false"
        maxlength="200"
        show-word-limit
        v-model="form.messageContent"
      ></van-field>
      <div class="access">
        <p class="title">附件</p>
        <van-field style="padding: 0" :border="false">
          <template #input>
            <van-uploader
              v-model="uploader"
              :before-read="beforeRead"
              :before-delete="beforDelete"
              :after-read="afterRead"
              :max-count="1"
              accept="*.*"
            >
              <!-- accept="image/*, .pdf" -->
              <!-- <div class="file">
                <img src="./images/icon_url.png" class="icon_url" />
                <div class="uploder-txt">
                  <p style="color: #1A1A1A; font-size: .14rem;">上传附件</p>
                  <p class="tips">仅支持图片、PDF，最大上传5M。</p>
                </div>
              </div> -->
            </van-uploader>

            <!-- <template v-if="form.fileUrl">
              <div class="file" v-if="form.messageType === 'FILE'">
                <img src="./images/icon_file.png" />
                <span>{{ form.fileName }}</span>
              </div>
              <div class="file" v-if="form.messageType === 'IMG'">
                <van-image :src="form.fileUrl" class="img" />
                <span>{{ form.fileName }}</span>
              </div>
            </template> -->
          </template>
        </van-field>
        <p class="tips">仅支持图片、PDF。最大上传5M。</p>
      </div>
    </van-cell-group>

    <div class="btn-group">
      <van-button type="primary" round block @click="onSubmit">确定</van-button>
    </div>

    <van-popup v-model="timerStatus" position="bottom">
      <van-datetime-picker
        v-model="date"
        :formatter="formatter"
        :min-date="minDate"
        @cancel="timerStatus = false"
        @confirm="onConfirm"
      ></van-datetime-picker>
    </van-popup>

    <van-popup position="bottom" round v-model="groupStatus">
      <select-group @onSubmit="onChoise" :selectIds="selectIds" />
    </van-popup>
  </div>
</template>

<script>
import dayjs from "dayjs";
import Header from "@/components/header";
import SelectGroup from "./selectGroup";
import qs from "qs";
import { uploadFile } from "@/api/app";
import {
  imSendGroupMessageSend,
  imSendGroupMessageDelete,
  imSendGroupMessageUpdate,
  policy,
} from "./api";
import axios from "axios";
export default {
  name: "operation",
  components: { Header, SelectGroup },
  data() {
    const query = this.$route.query;
    // 选择的群组
    const targetIds = query.targetIds;
    return {
      type: query.type || "create",
      groupStatus: false,
      timerStatus: false,
      selectIds: targetIds ? targetIds.split(",") : [],
      uploader: query.fileUrl
        ? [{ url: query.fileUrl, file: { name: query.fileName } }]
        : [],
      date: null,
      minDate: new Date(),
      id: query.id,
      form: {
        fileName: query.fileName || "",
        fileUrl: query.fileUrl || "",
        messageContent: query.messageContent || "",
        messageType: query.messageType || "",
        sendType: query.sendType || "NOW",
        sendTime: query.sendTime || "",
        targetIds: targetIds || "",
      },
      ossUploadUrl: "https://ks3-cn-beijing.ksyuncs.com/daya",
      preUploadUrl: "https://daya.ks3-cn-beijing.ksyuncs.com",
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        KSSAccessKeyId: "",
        acl: "public-read",
        name: "",
      },
    };
  },
  methods: {
    checkFileType(type) {
      if (type.indexOf("pdf") != -1 || type.indexOf("image") != -1) {
        return true;
      } else {
        return false;
      }
    },
    beforeRead(file) {
      const isLt2M = file.size / 1000 / 1000 < 5;
      if (!isLt2M) {
        this.$toast("上传文件大小不能超过 5MB");
        return false;
      } else if (!this.checkFileType(file.type)) {
        this.$toast("上传文件类型不支持");
        return false;
      }
      return true;
    },
    beforDelete() {
      this.form.fileName = "";
      this.form.fileUrl = "";
      return true;
    },
    async afterRead(file) {
      // 上传头像
      // console.log(file);
      const form = this.form;
      try {
        file.status = "uploading";
        file.message = "上传中...";
        let tempName = file.file.name || "";
        const fileName = tempName && tempName.replace(/ /gi, "_");
        let key = new Date().getTime() + fileName;
        let objTemp = {
          filename: fileName,
          bucketName: this.bucket_name,
          postData: {
            filename: fileName,
            acl: "public-read",
            key: key,
            unknowValueField: [],
          },
        };

        const res = await policy(objTemp);
        const obj = {
          policy: res.data.policy,
          signature: res.data.signature,
          key: key,
          KSSAccessKeyId: res.data.kssAccessKeyId,
          acl: "public-read",
          name: fileName,
        };

        let formData = new FormData();
        for (let key in obj) {
          formData.append(key, obj[key]);
        }
        formData.append("file", file.file);
        await axios({
          method: "post",
          url: this.ossUploadUrl,
          data: formData,
        });
        const uploadUrl = this.preUploadUrl + "/" + key;
        file.status = "done";
        form.fileName = file.file.name;
        form.fileUrl = uploadUrl;
        form.messageType = this.onCheckFileType(file.file.type);

        // console.log(form);
      } catch (e) {
        //
        file.status = "failed";
        file.message = "上传失败";
        form.fileName = "";
        form.fileUrl = "";
        return false;
      }
      // this.$toast.loading({
      //   duration: 0,
      //   forbidClick: true,
      //   message: "上传中...",
      // });
      //
      // try {
      //   file.status = "uploading";
      //   file.message = "上传中...";
      //   let formData = new FormData();
      //   formData.append("file", file.file);
      //   let res = await uploadFile(formData);
      //   this.$toast.clear();
      //   let result = res.data;
      //   if (result.code == 200) {
      //     file.status = "done";
      //     form.fileName = file.file.name;
      //     form.fileUrl = result.data.url;
      //     form.messageType = this.onCheckFileType(file.file.type);
      //   } else {
      //     file.status = "failed";
      //     file.message = "上传失败";
      //     this.$toast(result.msg);
      //     form.fileName = "";
      //     form.fileUrl = "";
      //     return false;
      //   }
      // } catch (err) {
      //   this.$toast.clear();
      //   file.status = "failed";
      //   file.message = "上传失败";
      //   form.fileName = "";
      //   form.fileUrl = "";
      //   return false;
      // }
    },
    onCheckFileType(type) {
      if (type.indexOf("image") != -1) {
        return "IMG";
      } else if (type.indexOf("pdf") != -1) {
        return "FILE";
      }
      return "";
    },
    onDel() {
      this.$dialog
        .confirm({
          title: "提示",
          message: "确定删除吗？",
          confirmButtonColor: "#01C1B5",
        })
        .then(async () => {
          try {
            await imSendGroupMessageDelete({
              id: this.id,
            });
            this.$toast.success("删除成功");
            setTimeout(() => {
              this.$router.back();
            }, 1000);
          } catch {
            //
          }
        });
    },
    formatter(type, val) {
      if (type === "year") {
        return `${val}年`;
      } else if (type === "month") {
        return `${val}月`;
      } else if (type === "day") {
        return `${val}日`;
      } else if (type === "hour") {
        return `${val}时`;
      } else if (type === "minute") {
        return `${val}分`;
      }
      return val;
    },
    onChoise(item) {
      this.groupStatus = false;
      this.selectIds = item;
    },
    onConfirm(date) {
      this.form.sendTime = dayjs(date).format("YYYY-MM-DD HH:mm:ss");
      this.timerStatus = false;
    },
    async onSubmit() {
      try {
        const form = this.form;
        if (this.selectIds && this.selectIds.length <= 0) {
          this.$toast("请选择发送群组");
          return;
        }
        if (form.sendType == "TIMING" && !form.sendTime) {
          this.$toast("请选择发送时间");
          return;
        }
        if (!form.messageContent) {
          this.$toast("请输入消息内容");
          return;
        }
        form.targetIds = this.selectIds.join(",");
        if (this.type == "create") {
          await imSendGroupMessageSend(form);
          this.$toast.success("创建成功");
        } else {
          form.id = this.id;
          await imSendGroupMessageUpdate(form);
          this.$toast.success("修改成功");
        }
        setTimeout(() => {
          this.$router.back();
        }, 1000);
      } catch {
        //
      }
    },
  },
};
</script>

<style lang="less" scoped>
.operation {
  min-height: 100vh;
}
.cellGroup {
  margin: 0.1rem 0.14rem;
  border-radius: 0.1rem;
  overflow: hidden;
  .labelClass {
    font-size: 0.14rem;
    font-weight: 500;
    color: #333333;
  }
}
.class {
  display: flex;
  align-items: center;
  line-height: 0.18rem;
  background: #fff4f2;
  border-radius: 0.04rem;
  padding: 0 0.03rem;
  font-size: 0.12rem;
  color: #ff5c00;
  img {
    margin-left: 0.03rem;
    width: 0.05rem;
    height: 0.07rem;
  }
}
.access {
  padding: 0 16px 0.2rem;
  .title {
    font-size: 0.14rem;
    color: #999999;
    line-height: 0.28rem;
  }
  .file {
    display: flex;
    align-items: center;
    background: #f6f8f9;
    border-radius: 0.06rem;
    padding: 0.12rem;
    img {
      width: 0.22rem;
      height: 0.26rem;
      margin-right: 0.1rem;
    }

    .img {
      border-radius: 0.06rem;
      width: 0.4rem;
      height: 0.4rem;
      margin-right: 0.1rem;
      overflow: hidden;
    }

    .icon_url {
      width: 0.24rem;
      height: 0.29rem;
      margin-right: 0.1rem;
      overflow: hidden;
    }
  }
}
.tips {
  font-size: 0.13rem;
  color: #999999;
}
// /deep/.van-uploader {
//   width: 100%;
// }
// /deep/.van-uploader__wrapper {
//   display: block;
// }
.uploder-txt {
  p {
    line-height: 1.2;
  }
}
.btn-group {
  padding: 0 0.14rem;
}
</style>
