<template>
  <view style="background: #ffffff">
    <my_form
      ref="form"
      :form="form"
      @isUncomplete="isUncomplete"
      @onUploading="onUploading"
      @isShowAll="isShowAll"
    >
      <template v-if="isShow" slot="head">
        <view class="headportrait" hover-class="navigator-hover">
          <view class="content">
            <My_upload
              maxCount="1"
              ref="upload"
              @onLoading="imageOnLoading"
              @uploadCallback="uploadCallback"
            >
            </My_upload>
            <button
              class="avatar-box"
              open-type="chooseAvatar"
              @chooseavatar="onChooseAvatar"
            ></button>
            <view style="display: flex; align-items: center">
              <view
                style="
                  border-radius: 50%;
                  width: 56px;
                  height: 56px;
                  border: 2px solid #ffffff;
                "
              >
                <u--image
                  :width="56"
                  :height="56"
                  shape="circle"
                  :src="headportrait"
                >
                  <template v-slot:loading>
                    <u-loading-icon />
                  </template>
                </u--image>
              </view>

              <view :style="'width:' + tovw(255)" />
              <view class="iconfont icon-a-wodetiaozhuan" />
            </view>
          </view>
        </view>
      </template>
    </my_form>

    <view v-if="!origin" style="height: 70px" />
    <view class="footer">
      <view
        class="add"
        :class="uncomplete ? 'forbidden' : ''"
        hover-class="navigator-hover"
        @click="uncomplete || loading ? '' : submit()"
      >
        <u-loading-icon v-if="loading" />
        <block v-else>
          {{ origin == "my" ? "保存" : "保存名片" }}
        </block>
      </view>
    </view>
  </view>
</template>

<script>
import { formattedFiles } from "../../utils/settleFiles.js";
export default {
  data() {
    return {
      sys_enterpriseid: 0,
      form: [],
      attachmentids: [],
      uncomplete: true,
      onUpload: false,
      loading: false,
      headportrait:
        "https://yossys06593.obs.cn-east-3.myhuaweicloud.com:443/202406011717209838416B6150695f.webp",
      userid: 0,
      isShow: true,
      isSubmit: false,
      origin: "",
    };
  },
  onLoad(options) {
    this.userid = options.id;
    this.origin = options.origin;
    this.init();
    uni.setNavigationBarTitle({
      title: "修改名片",
    });
  },
  onUnload() {
    if (!this.isSubmit) this.$refs.form.deleteFiles();
  },
  methods: {
    onChooseAvatar(e) {
      let ext = e.detail.avatarUrl.substr(
        e.detail.avatarUrl.lastIndexOf(".") + 1
      );
      let name = `${Date.now()}.${ext}`;
      let temp = {
        name: name,
        type: "image",
        url: e.detail.avatarUrl,
      };
      this.afterRead({ file: [temp] });
    },

    afterRead({ file }) {
      const that = this;
      file.forEach((v) => {
        // #ifdef H5
        this.getArrayBuffer(v).then((data) =>
          that.handleUploadFile(this.requestType(v), data)
        );
        // #endif
        // #ifndef H5
        uni.getFileSystemManager().readFile({
          filePath: v.url,
          success: (data) =>
            that.handleUploadFile(this.requestType(v), data.data),
          fail: console.error,
        });
        // #endif
      });
    },
    /* 请求类型 */
    requestType(file) {
      // #ifdef H5
      var ext = file.name.substr(file.name.lastIndexOf(".") + 1);
      // #endif
      // #ifndef H5
      var ext =
        file.type.split("/")[1] ||
        file.url.substr(file.url.lastIndexOf(".") + 1) ||
        file.name.substr(file.name.lastIndexOf(".") + 1);
      // #endif
      //文件名称
      return {
        classname: "system.attachment.huawei.OBS",
        method: "getFileName",
        content: {
          filename: `${Date.now()}.${ext}`,
          filetype: ext,
          parentid: uni.getStorageSync("siteP").appfolderid,
        },
      };
    },
    handleUploadFile(file, data) {
      this.loading = true;
      this.$Http.basic(file).then((res) => {
        if (res.msg == "成功") {
          this.uploadFile(res.data, data);
        } else {
          uni.showToast({
            title: `${data.filename}.${data.serialfilename}`,
            icon: "none",
          });
        }
      });
    },
    getArrayBuffer(file) {
      return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open("GET", file.url, true);
        xhr.responseType = "blob";
        xhr.onload = function () {
          if (this.status == 200) {
            let myBlob = this.response;
            let files = new window.File([myBlob], file.name, {
              type: file.url.substr(file.url.lastIndexOf(".") + 1),
            }); // myBlob.type 自定义文件名
            const reader = new FileReader();
            reader.readAsArrayBuffer(files);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
          } else {
            reject(false);
          }
        };
        xhr.send();
      });
    },
    /* 上传成功反馈 */
    uploadFile(res, data) {
      var that = this;
      that.loading = true;
      uni.request({
        url: res.uploadurl,
        method: "PUT",
        data,
        header: {
          "content-type": "application/octet-stream",
        },
        success() {
          that.$Http
            .basic({
              classname: "system.attachment.huawei.OBS",
              method: "uploadSuccess",
              content: {
                serialfilename: res.serialfilename,
              },
            })
            .then((s) => {
              console.log("文件上传反馈", s);
              that.loading = false;
              if (!that.cutoff(s.msg))
                that.uploadCallback(
                  s.data.attachmentids,
                  "sys_users",
                  that.userid
                );
            })
            .catch((err) => {
              that.loading = false;
              console.error(err);
            });
        },
        fail(err) {
          that.loading = false;
          console.log(err);
        },
      });
    },

    init() {
      let form = [
        {
          key: "name",
          type: "text",
          label: "姓名",
          isMust: true, //是否必填
          value: "",
        },
        {
          key: "phonenumber",
          type: "text",
          label: "手机号",
          isMust: true, //是否必填
          value: "",
          placeholder: "请输入手机号",
          inputmode: "number",
          verify: [this.getReg("phonenumber")],
          getPhoneNumber: true,
        },
        {
          key: "email",
          type: "text",
          label: "邮箱",
          isMust: false, //是否必填
          value: "",
          verify: [this.getReg("email")],
        },
        {
          key: "address",
          type: "text",
          label: "地址",
          isMust: false, //是否必填
          value: "",
        },
      ];
      if (!this.origin) {
        form.push(
          {
            key: "remarks",
            type: "textarea",
            label: "自我介紹",
            isMust: false, //是否必填
            value: "",
          },
          {
            key: "tag",
            type: "tag",
            label: "印象标签",
            isMust: false, //是否必填
            marginTop: 10,
            maxlength: 10,
            placeholder: "请填写，最多十个字",
            verify: [
              {
                reg: "^.{1,10}$",
                errText: "限制1-10字!",
              },
            ],
            value: [],
          },
          {
            key: "attachmentids",
            type: "upload",
            label: "图片",
            placeholder: "可上传多个图片",
            accept: "image*/",
            ownertable: "temporary",
            ownerid: 999,
            usetype: "default",
            allowUpload: true,
            allowDelete: true,
            value: [],
            marginTop: 10,
          }
        );
      }
      this.$Http
        .basic({
          id: 20240514161502,
          content: {
            userid: this.userid,
          },
        })
        .then((res) => {
          console.log("获取个人信息", res);
          if (this.cutoff(res.msg)) return;
          if (res.msg == "成功") {
            this.headportraits = res.data.attinfos;
            this.headportrait =
              (this.headportraits.find((v) => v.usetype == "headportrait") &&
                this.headportraits.find((v) => v.usetype == "headportrait")
                  .url) ||
              this.headportrait;
            form = form.map((v) => {
              if (v.key == "attachmentids") {
                v.value = formattedFiles(
                  res.data.attinfos.filter(
                    (item) => item.usetype != "headportrait"
                  )
                );
              } else {
                v.value = res.data[v.key] || v.value;
              }
              return v;
            });
          }
          this.form = form;
        });
    },
    onUploading(ing) {
      this.onUpload = ing;
    },
    isUncomplete(uncomplete) {
      console.log(uncomplete);
      this.uncomplete = uncomplete;
    },
    submit() {
      this.loading = true;
      let that = this;
      this.$refs.form.submit().then((data) => {
        this.$Http.basic({
          id: 20220929090901,
          content: {
            ownertable: "sys_users",
            ownerid: this.userid,
            datatag: data.tag,
          },
        });
        this.$Http
          .basic({
            id: 20240511151602,
            content: {
              ...data,
            },
          })
          .then(async (res) => {
            this.loading = false;
            console.log("修改信息", res);
            if (this.cutoff(res.msg)) return;
            if (!this.origin && data.files.temporarys.length) {
              this.onUpload = true;
              await this.$Http
                .basic({
                  classname: "system.attachment.Attachment",
                  method: "createFileLink",
                  content: {
                    ownertable: "sys_users",
                    ownerid: res.data.userid,
                    usetype: "default",
                    attachmentids: data.files.temporarys,
                  },
                })
                .then(async (s) => {
                  this.isSubmit = true;
                  this.onUpload = false;
                  console.log("绑定附加", s);
                  if (this.cutoff(s.msg)) return;
                });
            }
            this.loading = true;

            if (!this.origin && data.files.linksids.length) {
              await this.$Http.basic({
                classname: "system.attachment.Attachment",
                method: "deleteFileLink",
                content: {
                  linksids: data.files.linksids,
                },
              });
            }

            if (this.attachmentids.length) {
              this.uploadCallback(
                this.attachmentids,
                "sys_users",
                this.userid
              ).then((s) => {
                if (s) getUserMsg();
              });
              if (this.headportraits.length)
                this.$Http.basic({
                  classname: "system.attachment.Attachment",
                  method: "deleteFileLink",
                  content: {
                    linksids: this.headportraits.map((v) => v.linksid),
                  },
                });
            } else {
              this.$Http.editUser(res.data.userid);
              uni.navigateBack();
            }
            //刷新首页用户信息
            this.$Http.refreshUserInfoData && this.$Http.refreshUserInfoData();
          });
      });
    },
    isShowAll(e) {
      this.isShow = !e;
    },
    imageOnLoading(e) {
      if (e) {
        this.uncomplete = true;
      } else {
        this.$refs.form.verify();
      }
    },
    uploadCallback(
      attachmentids,
      ownertable = "temporary",
      ownerid = "99999999"
    ) {
      if (ownertable == "temporary") this.imageOnLoading(true);
      return new Promise((resolve, reject) => {
        this.$Http
          .basic({
            classname: "system.attachment.Attachment",
            method: "createFileLink",
            content: {
              usetype: "headportrait",
              ownertable,
              ownerid,
              attachmentids,
            },
          })
          .then((res) => {
            console.log("绑定附件", res);
            if (ownertable == "temporary") this.imageOnLoading(false);
            if (this.cutoff(res.msg)) return resolve(false);
            this.headportrait = res.data[0].url;
            resolve(true);
            if (ownertable == "temporary" && this.linksid)
              this.$Http
                .basic({
                  classname: "system.attachment.Attachment",
                  method: "deleteFileLink",
                  content: {
                    linksids: [this.linksid],
                  },
                })
                .then((res) => {
                  console.log("处理删除附件", res);
                  if (this.cutoff(res.msg)) return;
                });
            if (ownertable == "temporary") {
              this.attachmentids = attachmentids;
              console.log(res.data[0], "结果");
              this.headportrait = res.data[0].url;
              this.linksid = res.data[0].linksid;
            }
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.headportrait {
  width: 100vw;
  padding-left: 10px;
  background: #fff;
  box-sizing: border-box;

  .content {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #dddddd;
    box-sizing: border-box;
    height: 76px;
    padding: 10px;
    padding-left: 0;
    position: relative;

    .avatar-box {
      width: 100%;
      height: 76px;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
    }

    .label {
      font-family: Source Han Sans SC, Source Han Sans SC;
      font-size: 14px;
      color: #666666;
      width: 110px;
    }
  }
}

.upload-type {
  display: flex;
  flex-direction: column;
  font-family: Source Han Sans SC, Source Han Sans SC;
  font-weight: 400;
  font-size: 16px;
  color: #333333;

  .type-line {
    padding: 12px 0;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    border-bottom: 1px #dddddd solid;

    .line-1 {
      display: flex;
      align-items: center;
      align-content: center;

      text {
        margin-right: 10px;
      }

      image {
        width: 24px !important;
        height: 24px !important;
      }
    }

    text {
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  width: 100vw;
  height: 65px;
  background: #ffffff;
  box-shadow: 0px -2px 6px 1px rgba(0, 0, 0, 0.16);
  box-sizing: border-box;
  padding: 5px 10px;
  display: flex;

  .add {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 45px;
    background: #c30d23;
    border-radius: 5px;
    font-family: PingFang SC, PingFang SC;
    font-size: 14px;
    color: #ffffff;
  }

  .forbidden {
    opacity: 0.6;
  }
}
</style>