<template>
  <view class="page_container">
    <custom-nav-bar :title="`发布${!!momentsType ? '视频' : '图文'}`">
      <view class="nav_right_action" slot="more">
        <u-button
          type="primary"
          :disabled="fileList.length === 0 && !content"
          size="mini"
          loadingSize="12"
          :loading="publishing"
          text="发布"
          @click="publish"
        >
        </u-button>
      </view>
    </custom-nav-bar>

    <view class="edit_area">
      <u-textarea
        v-model="content"
        count
        border="none"
        maxlength="150"
        height="120"
        placeholder="请输入"
      >
      </u-textarea>

      <view class="media_row">
        <u-upload
          :fileList="fileList"
          :accept="!!momentsType ? 'video' : 'image'"
          :capture="!!momentsType ? ['album'] : ['album', 'camera']"
          @afterRead="afterRead"
          @delete="deletePic"
          multiple
          :maxCount="9"
        ></u-upload>
      </view>
    </view>

    <view class="settings_row">
      <setting-item
        :icon="visible_icon"
        show-right
        :title="permission === 3 ? '不给谁看' : '谁可以看'"
        @click="chooseVisible"
      >
        <view class="choose_row" slot="right">{{ choosedNameStr }}</view>
      </setting-item>
      <setting-item
        :icon="notify_icon"
        show-right
        title="提醒谁看"
        @click="chooseRemind"
      >
        <view class="choose_row" slot="right">{{ getRemindStr }}</view>
      </setting-item>
    </view>
  </view>
</template>

<script>
import CustomNavBar from "../../../components/CustomNavBar/index.vue";
import SettingItem from "./SettingItem.vue";
import { ContactChooseTypes, CustomType, PageEvents } from "../../../constant";
import { getPurePath, toastWithCallback } from "../../../util/common";
import { publishMoments } from "../../../api/moments";
import IMSDK from "openim-uniapp-polyfill";
import { base64ToPath } from "image-tools";

const visible_icon = "https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_visible.png";
const notify_icon = "https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/moments_notify.png";
export default {
  components: {
    CustomNavBar,
    SettingItem,
  },
  data() {
    return {
      content: "",
      fileList: [],
      choosedUserInfoList: [],
      choosedGroupInfoList: [],
      remindUserInfoList: [],
      permission: 0,
      visible_icon,
      notify_icon,
      choosedNameStr: "公开",
      momentsType: 0,
      publishing: false,
    };
  },
  computed: {
    getRemindStr() {
      let str = "";
      this.remindUserInfoList.map((user) => (str += `${user.nickname}、`));
      return str.slice(0, str.length - 1);
    },
  },
  onLoad(options) {
    this.momentsType = JSON.parse(options.momentsType || "0");
  },
  methods: {
    publish() {
      this.publishing = true;
      const workMoment = {
        content: {
          type: this.momentsType,
          metas: this.fileList.map((file) => ({
            thumb: file.thumb,
            original: file.original || file.thumb,
          })),
          text: this.content,
        },
        permission: this.permission,
        atUserIDs: this.remindUserInfoList.map((user) => user.userID),
        permissionGroupIDs: this.choosedGroupInfoList.map(
          (group) => group.groupID,
        ),
        permissionUserIDs: this.choosedUserInfoList.map((user) => user.userID),
      };
      console.log(workMoment);
      publishMoments(workMoment)
        .then(() =>
          toastWithCallback("发布成功！", () => {
            uni.$emit(PageEvents.RefreshMoments);
            uni.navigateBack();
          }),
        )
        .catch((err) => {
          console.log(err);
          uni.$u.toast("发布失败！");
        })
        .finally(() => (this.publishing = false));
    },
    async uploadFile(path) {
      const nameIdx = path.lastIndexOf("/") + 1;
      const typeIdx = path.lastIndexOf(".") + 1;
      const fileName = path.slice(nameIdx);
      const fileType = path.slice(typeIdx);
      try {
        const {
          data: { url },
        } = await IMSDK.asyncApi(IMSDK.IMMethods.UploadFile, IMSDK.uuid(), {
          filepath: getPurePath(path),
          name: fileName,
          contentType: fileType,
          uuid: IMSDK.uuid(),
        });
        return url;
      } catch (error) {
        console.log(error);
        return "";
      }
    },
    afterRead(event) {
      console.log(event);
      let lists = [].concat(event.file);
      lists.map(async (item) => {
        const idx =
          this.fileList.push({
            ...item,
            status: "uploading",
            message: "上传中",
          }) - 1;

        const purePath = getPurePath(item.url);

        if (!!this.momentsType) {
          const { path } = await IMSDK.getVideoCover(purePath);
          const thumb = await this.uploadFile(getPurePath(path));
          const original = await this.uploadFile(purePath);
          this.fileList.splice(idx, 1, {
            ...this.fileList[idx],
            status: thumb && original ? "success" : "failed",
            message: "",
            thumb,
            original,
          });
        } else {
          const thumb = await this.uploadFile(purePath);
          this.fileList.splice(idx, 1, {
            ...this.fileList[idx],
            status: thumb ? "success" : "failed",
            message: "",
            thumb,
          });
        }
      });
    },
    deletePic(event) {
      this.fileList.splice(event.index, 1);
    },
    getWhoCanSee({
      choosedUserInfoList,
      choosedGroupInfoList,
      permission,
      choosedNameStr,
    }) {
      this.choosedUserInfoList = choosedUserInfoList;
      this.choosedGroupInfoList = choosedGroupInfoList;
      this.permission = permission;
      this.choosedNameStr = choosedNameStr;
      if (permission === 1) {
        this.remindUserInfoList = [];
      }
    },
    getCheckedUsers(data) {
      this.remindUserInfoList = [...data];
    },
    chooseVisible() {
      uni.$u.route("/pages_im/pages/moments/mementsVisibility/index", {
        choosedUserInfoList: JSON.stringify(this.choosedUserInfoList),
        choosedGroupInfoList: JSON.stringify(this.choosedGroupInfoList),
        permission: this.permission,
        choosedNameStr: this.choosedNameStr,
      });
    },
    chooseRemind() {
      if (this.permission === 1) {
        uni.$u.toast("可见范围为私密时，此功能不可用！");
        return;
      }
      uni.$u.route("/pages_im/pages/common/contactChoose/index", {
        type: ContactChooseTypes.GetList,
        checkedUserInfoList: JSON.stringify(this.remindUserInfoList),
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.page_container {
  background-color: #f8f8f8;

  .nav_right_action {
    margin-right: 44rpx;

    .u-button--mini {
      height: 52rpx;
    }
  }

  .edit_area {
    padding: 32rpx;
    background-color: #fff;
    margin-top: 24rpx;

    .u-textarea {
      padding: 0;
    }
  }

  .settings_row {
    margin-top: 24rpx;

    .choose_row {
      @include nomalEllipsis;
      max-width: 300rpx;
    }
  }
}
</style>
