<template>
  <gui-page :custom-header="true" :header-class="['gui-theme-background-color']">
    <template #gHeader>
      <view style="height:44px;" class="gui-flex gui-nowrap gui-rows gui-align-items-center">
        <!-- 使用组件实现返回按钮及返回首页按钮 -->
        <text
          style="font-size:44rpx;"
          class="gui-header-leader-btns gui-color-white font-icons"
          @tap="goBack"
        >&#xe6c5;</text>
        <!-- 导航文本此处也可以是其他自定义内容 -->
        <text
          class="gui-h4 gui-blod gui-flex1 gui-text-center gui-ellipsis gui-color-white gui-primary-text"
        >生产结束</text>
        <!-- 此处加一个右侧展位元素与左侧同宽，实现标题居中 -->
        <!-- 实际宽度请根据自己情况设置 -->
        <view style="width:40px;" />
        <!-- 如果右侧有其他内容可以利用条件编译和定位来实现-->
      </view>
    </template>
    <template #gBody>
      <view class="list-content">
        <view class="table-title" style="margin-top: 16px;">
          <span>图片列表</span>
        </view>
        <view class="photo-list">
          <view v-for="(item, key) in photoList" :key="key" class="photo-card">
            <image
              :src="item"
              class="photo"
              mode="scaleToFill"
              @click="handleRemoveImage(item, key)"
            />
          </view>
        </view>
      </view>
      <gui-right-menus>
        <!-- 扩展按钮 -->
        <template #menus-more>
          <view
            hover-class="gui-tap"
            class="menu-items gui-bg-blue gui-flex gui-columns gui-justify-content-center"
            @click="takePhoto"
          >
            <text class="menu-text gui-block gui-text-center gui-color-white">拍照</text>
          </view>
          <view
            hover-class="gui-tap"
            class="menu-items gui-bg-green gui-flex gui-columns gui-justify-content-center"
            @click="handleComplete"
          >
            <text class="menu-text gui-block gui-text-center gui-color-white">结束</text>
          </view>
        </template>
        <!-- 核心按钮 -->
        <template #menus-primary>
          <view class="menu-items gui-bg-primary gui-flex gui-columns gui-justify-content-center">
            <text class="menu-icon gui-color-white gui-block gui-text-center gui-icons">&#xe614;</text>
            <text class="menu-text gui-color-white gui-block gui-text-center">操作</text>
          </view>
        </template>
      </gui-right-menus>
    </template>
  </gui-page>
</template>

<script>
import axios from 'axios'
import {
  ref,
  defineComponent,
  onBeforeMount
} from 'vue'
export default defineComponent({
  setup() {
    const parentRow = uni.getStorageSync('HotPressInfo') ?? {}
    const hotPressId = ref('')
    const photoList = ref([])
    const fileIds = ref([])

    onBeforeMount(() => {
      hotPressId.value = JSON.parse(parentRow)?.id
    })

    const goBack = function() {
      uni.$goBack('/pages/workbranch/production/processExecution/processExecution')
    }

    const takePhoto = function() {
      uni.chooseImage({
        count: 6, // count: 6, //默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 从相册选择
        success: function(res) {
          res.tempFilePaths.forEach(async item => {
            // #ifdef APP-PLUS
            // 移动端无法使用FormData类型
            // 使用uniapp官方提供的uploadFile函数替代实现文件上传
            await uni.uploadFile({
              url: uni.$baseUrl +
									'/admin-api/minio/files/uploadFiles',
              name: 'file',
              filePath: item,
              header: {
                'Authorization': 'Bearer ' + uni
                  .getStorageSync('token')
              },
              success: function(uploadFileRes) {
                const resultJSON = JSON.parse(
                  uploadFileRes.data)
                if (fileIds.value == null) {
                  fileIds.value = []
                }
                fileIds.value.push(resultJSON.data
                  .fileId)
              }
            })
            // #endif
            photoList.value.push(item)
          })
          // #ifdef H5
          res.tempFiles.forEach(async item => {
            const formData = new FormData()
            formData.append('file', item)
            // 上传文件
            const {
              data
            } = await axios({
              url: uni.$baseUrl +
									'/admin-api/minio/files/uploadFiles',
              name: '上传文件',
              method: 'post',
              headers: {
                'Authorization': 'Bearer ' + uni.getStorageSync('token'),
                'Content-Type': 'multipart/form-data;'
              },
              data: formData
            })
            if (fileIds.value == null) {
              fileIds.value = []
            }
            fileIds.value.push(data.data.fileId)
          })
          // #endif
        }
      })
    }

    const handleRemoveImage = function(opt, index) {
      fileIds.value.splice(index, 1)
      photoList.value.splice(index, 1)
    }

    const handleComplete = function() {
      // 生产执行
      uni.$reqPost('completeProduction', {
        hotPressId: hotPressId.value,
        fileIdList: fileIds.value
      })
        .then(({
          code,
          data,
          msg
        }) => {
          if (code === 0) {
            uni.showToast({
              title: '执行结束，标签打印中',
              icon: 'none',
              duration: 2000
            })
          } else {
            uni.showToast({
              title: msg,
              icon: 'none',
              duration: 2000
            })
          }
        })
    }

    return {
      goBack,
      photoList,
      takePhoto,
      handleComplete,
      handleRemoveImage
    }
  }
})
</script>

<style lang="scss" scoped>
	.gui-header-leader-btns {
		color: black;
		font-size: 24px !important;
		margin-left: 24rpx;
	}

	.list-content {
		margin-top: 80px;
		background-color: #edeeee;
	}

	.table-title {
		height: 40px;
		line-height: 40px;
		margin: 0 0 -3px 0;
		padding: 0 12px;
		font-size: 16px;
		font-weight: bold;
		background-color: white;
	}

	.photo-list {
		display: grid;
		grid-template-rows: max-content;
		grid-template-columns: 1fr 1fr;

		.photo-card {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 8px 0;

			.photo {
				width: calc(100vw / 2 - 12px);
				height: calc(100vw / 3.2 - 6px);
				border-radius: 8px;
				pointer-events: none;
			}

			.photo::after {
				content: "×";
				width: 22px;
				height: 22px;
				position: absolute;
				top: 5px;
				right: 5px;
				display: flex;
				justify-content: center;
				align-items: center;
				color: rgba(255, 255, 255, 0.9);
				background-color: rgba(0, 0, 0, 0.5);
				border-radius: 50%;
				font-size: 24px;
				/*给伪元素开启鼠标事件，将事件冒泡到父元素的点击事件中*/
				pointer-events: auto;
			}
		}
	}
</style>
