<template>
  <view>
    <cu-custom bgImage="/static/bg.png" :isBack="true">
      <template v-slot:content>
        {{ title }}
      </template>
    </cu-custom>

    <view class="padding">
      <view class="padding-xl text-center">
        <image :src="group.avatar" class="cu-avatar round xl logo-xxl" mode="aspectFill" @tap="chooseImage"></image>
      </view>
      <uni-forms ref="groupForm" :model="group" :label-width="80" :rules="rules">
        <uni-forms-item label="群名称" name="name">
          <uni-easyinput type="text" v-model="group.name"/>
        </uni-forms-item>
        <uni-forms-item label="开启邀请">
          <switch @change="openInviteSwitch" :class="openInvite?'checked':''" :checked="openInvite"/>
        </uni-forms-item>
        <uni-forms-item label="邀请审核" v-if="showInviteCheck">
          <switch @change="inviteCheckSwitch" :class="inviteCheck?'checked':''" :checked="inviteCheck"/>
        </uni-forms-item>
        <uni-forms-item label="全体禁言">
          <switch @change="prohibitionSwitch" :class="prohibition?'checked':''" :checked="prohibition"/>
        </uni-forms-item>
        <uni-forms-item label="禁加好友">
          <switch @change="prohibitFriendSwitch" :class="prohibitFriend?'checked':''" :checked="prohibitFriend"/>
        </uni-forms-item>

        <view class="cu-bar bg-white">
          <button class="cu-btn bg-cyan lg margin-top" style="width: 100%;" @tap="save">保存</button>
        </view>
      </uni-forms>
    </view>

  </view>
</template>

<script setup lang="ts">
import {getCurrentInstance, reactive, ref} from "vue";
import CuCustom from '@/colorui/components/cu-custom.vue'
import GroupApi from "@/api/GroupApi";
import MessageUtils from "@/utils/MessageUtils";
import Auth from "@/api/Auth";
import FetchRequest from "@/api/FetchRequest";
import {onLoad} from '@dcloudio/uni-app';
import ChatType from "@/utils/ChatType";
import {useChatStore} from "@/store/chatStore";
import type Group from "@/mode/Group";
import {useGroupStore} from "@/store/groupStore";
import UniForms from "@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import UniFormsItem from "@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniEasyinput from "@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import VimConfig from "@/config/VimConfig";

const groupStore = useGroupStore();
const chatStore = useChatStore();
//@ts-ignore
const {proxy} = getCurrentInstance();
const map = ref(new Map());
const hidden = ref(true);
const title = ref('新建群组');

const rules = {
  name: {
    rules: [
      {
        required: true,
        errorMessage: '请输入群名称',
      },
      {
        minLength: 2,
        maxLength: 8,
        errorMessage: '群名称长度在 {minLength} 到 {maxLength} 个字符',
      }
    ]
  }
}
const group = reactive<Group>({
  id: "",
  master: "",
  name: '',
  avatar: '',
  openInvite: '0',
  inviteCheck: '0',
  prohibition: '0',
  prohibitFriend: '0',
  announcement: ''
})

const groupForm = ref();
const openInvite = ref(false);
const showInviteCheck = ref(false);
const inviteCheck = ref(false);
const prohibition = ref(false);
const prohibitFriend = ref(false);

const openInviteSwitch = (e: any) => {
  openInvite.value = e.detail.value
  openInviteChange();
}

const inviteCheckSwitch = (e: any) => {
  inviteCheck.value = e.detail.value
}

const prohibitionSwitch = (e: any) => {
  prohibition.value = e.detail.value
}

const prohibitFriendSwitch = (e: any) => {
  prohibitFriend.value = e.detail.value
}

/**
 * 开启邀请改变
 */
const openInviteChange = () => {
  if (openInvite.value) {
    showInviteCheck.value = true
  } else {
    showInviteCheck.value = false
  }
}

/**
 * 初始化
 */
onLoad((opt) => {
  if (opt?.id) {
    group.id = opt.id;
    GroupApi.get(group.id)
        .then((res) => {
          group.id = res.data.id;
          group.name = res.data.name;
          group.avatar = res.data.avatar;
          group.announcement = res.data.announcement;
          group.openInvite = res.data.openInvite;
          group.inviteCheck = res.data.inviteCheck;
          group.prohibition = res.data.prohibition;
          group.prohibitFriend = res.data.prohibitFriend;
          openInvite.value = res.data.openInvite === '1';
          openInviteChange();
          inviteCheck.value = res.data.inviteCheck === '1';
          prohibition.value = res.data.prohibition === '1';
          prohibitFriend.value = res.data.prohibitFriend === '1';
          title.value='编辑群组'
        })
  }
})

const chooseImage = () => {
  uni.chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: (res) => {
      uni.uploadFile({
        url: `${FetchRequest.getHost()}/${VimConfig.uploadType}/upload`, //仅为示例，非真实的接口地址
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          "Access-Control-Allow-Origin": "*",
          "Authorization": "Bearer " + Auth.getToken(),
        },
        formData: {
          'type': 'image'
        },
        success: (res) => {
          group.avatar = JSON.parse(res.data).url
        },
        fail: () => {
          MessageUtils.error('上传失败')
        },
      });
    }
  });
}

const save = () => {
  groupForm.value.validate().then(() => {
    // //新增
    if (!group.id) {
      GroupApi.save(group.name, group.avatar, openInvite.value ? '1' : '0', inviteCheck.value ? '1' : '0',prohibition.value ? '1' : '0',prohibitFriend.value ? '1' : '0', group.announcement)
          .then(() => {
            MessageUtils.message('保存成功')
            groupStore.loadGroupList();

            uni.navigateBack()
          })
          .catch((err) => {
            MessageUtils.error(err)
          })
    } else {
      GroupApi.update(group.id, group.name, group.avatar, openInvite.value ? '1' : '0', inviteCheck.value ? '1' : '0',prohibition.value ? '1' : '0',prohibitFriend.value ? '1' : '0', group.announcement)
          .then(() => {
            MessageUtils.message('更新成功')
            chatStore.updateChat(group.id, group.name, group.avatar)
            groupStore.loadGroupList();
            uni.navigateTo({
              url: '/pages/group/group?id=' + group.id
            })
          })
          .catch((err) => {
            MessageUtils.error(err)
          })
    }
  }).catch((err: any) => {
    console.log('表单错误信息：', err);
  })
}

</script>

<style scoped>
.title {
  color: #666666;
  text-align: left;
  width: 150upx;
}

.border {
  border: 1px solid #ccc;
  padding: 10upx;
  min-height: 70upx;
}
</style>
