<template>
  <view>
    <Navbar title="检验入库" :showRightText="true" :isBack="false" :text="'已检验'" @chickIcon="handleRightText" />
    <div class="cont">
      <!-- 搜索 -->
      <div class="search">
        <u-input
          v-model="keyWord"
          placeholder="请输入搜索关键词"
          suffixIcon="search"
          suffixIconStyle="color: #666"
          shape="circle"
          @blur="handleSearch"
        ></u-input>
      </div>
      <!-- 列表 -->
      <div class="list-cont" v-for="(item, index) in tableList" :key="index" @click="handleCheck(item)">
        <u-row justify="space-between" customStyle="margin-bottom: 10px; padding: 0 15px;">
          <u-col span="6">
            <div>{{ item.name }}</div>
          </u-col>
          <u-col span="6">
            <div style="text-align: end; color: #999">{{ item.model }}</div>
          </u-col>
        </u-row>
        <u-line style="margin-bottom: 5px"></u-line>
        <div class="list-item">
          <span>退 回 量：</span>
          <span style="color: #5ae725">{{ item.backNum }}</span>
        </div>
      </div>

      <u-loadmore :status="status" line v-if="tableList.length > 10" />

      <!-- 空状态 -->
      <u-empty v-if="tableList.length == 0" mode="data"></u-empty>
    </div>

    <!-- 弹出层 -->
    <u-popup :show="showType" mode="center" :closeOnClickOverlay="false" round="8">
      <div class="uPopup">
        <div class="pop-title">检验鉴定</div>
        <div class="top-box">
          <u-row justify="space-between" customStyle="margin-bottom: 10px;">
            <u-col span="6">
              <div>{{ pop.name }}</div>
            </u-col>
            <u-col span="6">
              <div style="text-align: end">{{ pop.model }}</div>
            </u-col>
          </u-row>
          <div class="list-item">
            <span>退 回 量：</span>
            <span>{{ pop.backNum }}</span>
          </div>
        </div>
        <u-line style="margin-bottom: 10px"></u-line>
        <u-form :model="formData" :rules="rules" ref="uForm" labelWidth="auto" labelPosition="left">
          <u-form-item label="经办人" prop="manager" borderBottom required>
            <u-input v-model="formData.manager" placeholder="请输入经办人" border="none" inputAlign="right"></u-input>
          </u-form-item>
          <u-form-item label="经办日期" prop="checkTime" borderBottom required>
            <u-cell-group :border="false">
              <u-cell
                isLink
                :label="formData.checkTime ? '' : '请选择经办日期'"
                :value="formData.checkTime"
                :border="false"
                @click="showPickerTime = true"
              ></u-cell>
            </u-cell-group>
          </u-form-item>
          <u-form-item label="可继续使用数量" prop="goodNum" borderBottom required>
            <u-input
              v-model="formData.goodNum"
              type="number"
              placeholder="请输入可继续使用数量"
              border="none"
              inputAlign="right"
            ></u-input>
          </u-form-item>
          <u-form-item label="待报废量" prop="scrapNum" borderBottom required>
            <u-input
              v-model="formData.scrapNum"
              type="number"
              placeholder="请输入待报废量"
              border="none"
              inputAlign="right"
            ></u-input>
          </u-form-item>
          <u-form-item label="备注" prop="remark" required>
            <u-textarea v-model="formData.remark" placeholder="请输入备注" :rows="5" maxlength="200" count></u-textarea>
          </u-form-item>
          <u-form-item label="附件" prop="fileList">
            <uni-file-picker
              v-model="formData.fileList"
              :auto-upload="false"
              ref="files"
              limit="3"
              @select="selectImg"
              @delete="deleteImg"
              :readonly="false"
            />
          </u-form-item>
        </u-form>
        <div style="height: 35px"></div>
        <div class="btn">
          <u-button plain text="取消" style="margin: 8px 0" @click="showType = false"></u-button>
          <u-button type="success" plain text="确定" style="margin: 8px 0" @click="submit"></u-button>
        </div>
      </div>
    </u-popup>

    <!-- 日期 -->
    <u-datetime-picker
      v-if="showPickerTime"
      :show="showPickerTime"
      v-model="dataTime"
      :max-date="Number(new Date())"
      mode="date"
      @cancel="showPickerTime = false"
      @confirm="confirmTime"
    ></u-datetime-picker>
    <!-- loading -->
    <u-loading-page :loading="isLoading" icon-size="39" style="z-index: 99999"></u-loading-page>
  </view>
</template>

<script>
import config from '@/config'
import { getCheckList, checkAppraise } from '@/api/aqSafety'

export default {
  data() {
    return {
      actionUrl: config.baseUrl + config.uploadFileUrl,
      token: uni.getStorageSync('App-Token'),
      isLoading: false,
      showPickerTime: false,
      dataTime: Number(new Date()),
      keyWord: '',
      status: 'loadmore',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableList: [],
      showType: false,
      inventoryPopList: [],
      typePopName: '',
      pop: {},
      formData: {
        modelId: '', // 安全工器具id
        manager: '', // 经办人
        checkTime: '', // 经办日期
        goodNum: '', // 可继续使用数量
        scrapNum: '', // 待报废量
        remark: '', // 备注
        fileList: [], // 上传图片-处理前
        uploadPaths: [] // 上传图片-处理后
      },
      rules: {
        manager: [{ required: true, message: '请输入经办人', trigger: 'blur' }],
        checkTime: [{ required: true, message: '请选择经办日期', trigger: 'blur' }],
        goodNum: [
          { required: true, message: '请输入可继续使用数量', trigger: 'blur' },
          // 正则校验 正整数
          {
            validator: (rule, value, callback) => {
              if (!/^[0-9]\d*$/.test(value)) {
                callback(new Error('请输入正整数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        scrapNum: [
          { required: true, message: '请输入待报废量', trigger: 'blur' },
          // 正则校验 正整数
          {
            validator: (rule, value, callback) => {
              if (!/^[0-9]\d*$/.test(value)) {
                callback(new Error('请输入正整数'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      }
    }
  },
  onLoad() {
    this.getList()
  },
  methods: {
    handleSearch() {
      this.pageSize = 10
      this.getList()
    },
    async getList() {
      try {
        const params = {
          encryptedData: JSON.stringify({ keyWord: this.keyWord }),
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
        console.log('🚀 ~ getList ~ params', params)
        const res = await getCheckList(params)
        console.log('🚀 ~ getList ~ res', res)
        this.tableList = res.data.list
        this.total = res.data.total
      } catch (error) {
        console.log('🚀 ~ getList ~ error', error)
      }
    },
    onReachBottom() {
      console.log('🚀 ~ onReachBottom ~ ')
      if (this.total < 10 || this.total == this.tableList.length) {
        this.status = 'nomore'
        return
      }
      this.status = 'loading'
      setTimeout(() => {
        this.pageSize += 10
        this.getList()
        if (this.tableList.length != this.total) this.status = 'loadmore'
        else this.status = 'nomore'
      }, 500)
      console.log('加载..', this.pageSize)
    },
    handleRightText() {
      console.log('🚀 ~ handleRightText ~ ')
      uni.navigateTo({
        url: '/pages/inspectionEntry/inspectionRecord'
      })
    },
    handleCheck(item) {
      console.log('🚀 ~ handleCheck ~ item:', item)
      this.pop = item
      this.showType = true
      // 清空表单
      this.$nextTick(() => {
        // this.$refs.uForm.resetFields()
        this.formData = {
          modelId: item.id,
          manager: '', // 经办人
          checkTime: '', // 经办日期
          goodNum: '', // 可继续使用数量
          scrapNum: '', // 待报废量
          remark: '', // 备注
          fileList: [], // 上传图片-处理前
          uploadPaths: [] // 上传图片-处理后
        }
      })
    },
    // 日期选择器
    confirmTime(e) {
      console.log('🚀 ~ confirmTime ~ e', e)
      this.formData.checkTime = this.formatTimestamp(e.value)
      console.log('🚀 ~ confirmTime ~ this.formData.checkTime:', this.formData.checkTime)
      this.showPickerTime = false
    },
    // 将时间戳转换为日期格式 yyyy-MM-dd
    formatTimestamp(timestamp) {
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    selectImg(e) {
      console.log('🚀 ~ selectImg ~ e:', e)
      e.tempFiles.forEach(file => {
        this.formData.fileList.push(file)
      })
      console.log('🚀 ~ selectImg ~ this.formData:', this.formData)
    },
    deleteImg(e) {
      console.log('🚀 ~ deleteImg ~ e:', e)
      this.formData.fileList.splice(e.index, 1)
      console.log('🚀 ~ deleteImg ~ this.formData.fileList:', this.formData.fileList)
    },
    upload(path) {
      uni.uploadFile({
        url: this.actionUrl,
        filePath: path,
        name: 'file',
        header: {
          Authorization: this.token
        },
        success: res => {
          console.log('🚀 ~ selectImg ~ res:', res)
          console.log('🚀 ~ selectImg ~ res--data:', JSON.parse(res.data).data)
          this.formData.uploadPaths.push(JSON.parse(res.data).data)
          // console.log('🚀 ~ upload ~ this.handlePhotoList:', this.formData.handlePhotoList)
        },
        fail: err => {
          console.log('🚀 ~ selectImg ~ err:', err)
        }
      })
    },
    // 提交
    submit() {
      console.log('🚀 ~ submit ~ ')
      console.log('🚀 ~ submit ~ this.formData:', this.formData)
      // 可继续使用量+待报废量 不能大于 退回量
      if (Number(this.formData.goodNum) + Number(this.formData.scrapNum) > this.pop.backNum) {
        this.$modal.msg('可继续使用量、待报废量总数不能超过退回量')
        return
      }
      // 校验表单
      this.$refs.uForm.validate().then(res => {
        console.log('🚀 ~ submit ~ 提交-校验通过')
        this.isLoading = true
        this.formData.uploadPaths = []
        const uploadPromises = this.formData.fileList.map(async file => {
          console.log('🚀 ~ uploadFile ~ file:', file)
          return this.upload(file.path)
        })

        Promise.all(uploadPromises)
          .then(() => {
            console.log('所有文件上传完成')
            setTimeout(async () => {
              try {
                const params = {
                  ...this.formData,
                  backNum: this.pop.backNum,
                  modelId: this.pop.id
                }
                delete params.fileList
                console.log('🚀 ~ submit ~ params:', params)
                const encryptedData = JSON.stringify(params)
                const res = await checkAppraise({ encryptedData })
                console.log('🚀 ~ submit ~ res:', res)
                this.isLoading = false
                this.$modal.msg('提交成功')
                this.showType = false
                setTimeout(() => {
                  // 刷新页面
                  this.getList()
                }, 200)
              } catch (error) {
                console.log('🚀 ~ submit ~ error', error)
                this.isLoading = false
              }
            }, 600)
          })
          .catch(error => {
            console.error('文件上传过程中出现错误:', error)
            this.isLoading = false
          })
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #f8f8f8;
}
.cont {
  padding: 15px;
}
.search {
  margin-bottom: 15px;
}
.list-cont {
  padding: 15px 0;
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);

  .list-item {
    padding: 5px 15px;
  }
}
.uPopup {
  width: 90vw;
  min-height: 80vh;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-sizing: border-box;
  .pop-title {
    font-size: 16px;
    font-weight: 800;
    margin-bottom: 10px;
    text-align: center;
    color: #777;
  }

  .top-box {
    padding: 15px;
    background-color: #7dd5a9;
    color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  }

  .btn {
    position: absolute;
    bottom: 0px;
    width: calc(90vw - 30px);
    display: flex;
  }
}
</style>
