<template>
  <div class="full-width flex">
    <div class="flex flex-col flex-justify-around flex-center full-height">
      <div class="bold font-16" style="margin-top: -10px">我的信息</div>
      <div class="mt-10 ml-20" @click="show = true">
        <el-avatar :src="user.info.avatarUrl" :size="100"></el-avatar>
        <el-icon :size="25" style="margin-left: -30px">
          <EditPen />
        </el-icon>
      </div>
      <div class="mt-10" style="margin-left: 33px">
        {{ user.info.nickName }}
      </div>
    </div>
    <div
      class="flex flex-col flex-child-average mt-20"
      style="margin-left: 60px"
    >
      <el-input
        :placeholder="placeholder"
        size="large"
        maxlength="6"
        v-model="status"
        class="input"
      ></el-input>
      <div
        class="flex flex-center flex-justify-between mt-10 padding-left padding-right"
      >
        <el-tooltip
          v-for="icon in icons"
          :key="icon.value"
          :content="icon.tips"
        >
          <img
            :src="icon.icon"
            class="icon-task pointer"
            @click="changeWorkStatus(icon)"
          />
        </el-tooltip>
      </div>
    </div>

    <el-dialog title="修改头像" v-model="show" width="780px" @close="close">
      <div>
        <div>
          <span
            class="full-width text-left flex flex-justify-start padding-top padding-bottom"
          >
            新头像不允许涉及政治敏感与色情;<br />
            图片格式必须为：png,jpeg,jpg；不可大于2M；<br />
            建议使用png格式图片，以保持最佳效果；建议图片尺寸为144px*144px
          </span>
          <div class="flex flex-justify-start padding-bottom">
            <upload-office
              accept=".jpg,.png,.jpeg"
              :max="1"
              :show-progress="false"
              @upload="upload"
            />
          </div>
        </div>
        <el-divider />
        <div class="flex flex-justify-start">
          <div class="ml-20 flex flex-justify-start flex-col">
            <div class="bold text-left">头像裁剪</div>
            <div class="mt-20 upload flex flex-center">
              <cropper
                ref="cropper"
                class="cropper"
                :src="img"
                :stencil-props="{
                  aspectRatio: 1 / 1,
                  resizable: false
                }"
                @change="changeAvatar"
              ></cropper>
            </div>
          </div>
          <div class="ml-20 flex flex-justify-start flex-col">
            <div class="bold text-left">头像预览</div>
            <div class="mt-20 preview flex flex-center">
              <el-avatar
                v-if="previewImg"
                :size="114"
                fit="fill"
                :src="previewImg"
              ></el-avatar>

              <el-avatar
                v-if="previewImg"
                :size="114"
                shape="square"
                fit="fill"
                class="ml-20"
                :src="previewImg"
              ></el-avatar>
            </div>
          </div>
        </div>
        <div class="mt-20 full-width flex flex-justify-end">
          <el-button type="primary" plain @click="show = false"
            >取 消
          </el-button>
          <el-button type="primary" @click="uploadImage">确 定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { useStore } from '@/store/user.js'
import { Cropper } from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'
import api from '@/api/index.js'
import website from '@/config/website.js'
import { getToken } from '@/utils/auth.js'
import { Base64 } from 'js-base64'
import uploadOffice from '@/components/upload-office/index.vue'

export default {
  components: {
    Cropper,
    uploadOffice
  },
  setup() {
    const user = useStore()
    return { user }
  },

  watch: {
    status: {
      handler(val) {
        if (val.length > 0) {
          setTimeout(() => {
            this.update()
          }, 2000)
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      show: false,
      status: '',
      img: '',
      previewImg: '',
      placeholder: '请填写状态（最长6个字符）',
      id: '',
      headers: {
        Authorization: `Basic ${Base64.encode(
          `${website.clientId}:${website.clientSecret}`
        )}`,
        'Blade-Auth': 'bearer ' + getToken()
      },
      icons: [
        {
          icon: new URL('../../../assets/svg/task/work.svg', import.meta.url)
            .href,
          tips: '沉迷工作',
          value: 0
        },
        {
          icon: new URL('../../../assets/svg/task/trip.svg', import.meta.url)
            .href,
          tips: '出差',
          value: 1
        },
        {
          icon: new URL('../../../assets/svg/task/leave.svg', import.meta.url)
            .href,
          tips: '休假',
          value: 2
        },
        {
          icon: new URL('../../../assets/svg/task/stay.svg', import.meta.url)
            .href,
          tips: '休息',
          value: 3
        }
      ]
    }
  },
  created() {
    this.info()
  },
  methods: {
    info() {
      this.$api.dash.workInfo().then(res => {
        if (res.code === 200) {
          this.placeholder = res.data.workStatusDescribe
            ? res.data.workStatusDescribe
            : '请填写状态（最长6个字符）'
          this.id = res.data.id === -1 ? '' : res.data.id
        } else {
          console.log(res)
        }
      })
    },
    update() {
      if (this.status.length === 0) {
        return
      }
      this.$api.dash
        .submit({ id: this.id, workStatusDescribe: this.status })
        .then(res => {
          if (res.code === 200) {
            console.log(res)
          } else {
            console.log(res)
          }
        })
    },
    changeWorkStatus(res) {
      this.status = res.tips
    },
    upload(list) {
      this.previewImg = list[0].filePath
      this.img = list[0].filePath
    },
    changeAvatar({ coordinates, image, canvas }) {
      this.previewImg = canvas.toDataURL()
    },
    uploadImage() {
      const { canvas } = this.$refs.cropper.getResult()
      if (canvas) {
        const form = new FormData()
        canvas.toBlob(blob => {
          form.append('file', blob)
          // You can use axios, superagent and other libraries instead here
          fetch(api.uploadPath, {
            method: 'POST',
            headers: this.headers,
            body: form
          })
            .then(response => response.json())
            .then(body => {
              if (body.code === 200) {
                this.updateAvatar(body.data.filePath)
              }
            })
        }, 'image/png')
      }
    },
    updateAvatar(avatar) {
      const data = {
        id: this.user.info.userId,
        deptId: this.user.info.deptId,
        avatar
      }
      this.$api.dash.updateAvatar(data).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.user.info.avatarUrl = avatar
          this.user.setUserInfo(this.user.info)
          this.show = false
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    close() {
      this.img = ''
      this.previewImg = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.preview {
  background-color: #eeeeee;
  height: 240px;
  width: 360px;
  border-radius: 8px;
}

.upload {
  background-color: #eeeeee;
  height: 240px;
  width: 320px;
  border-radius: 8px;
}

.icon-task {
  width: 38px;
  height: 45px;
  object-fit: fill;
}

.cropper {
  width: 280px;
  height: 280px;
}

.input {
  height: 100px;

  :deep(.el-input__wrapper) {
    background-color: #eeeeee;
  }
}
</style>
