<template>
  <view>
    <Navbar title="退料清点" :showRightText="true" :isBack="false" :text="'退料记录'" @chickIcon="handleRightText" />
    <uni-section title="退料信息填写" type="line"></uni-section>
    <div class="cont">
      <u-form :model="formData" :rules="rules" ref="uForm" labelWidth="auto" labelPosition="left" errorType="toast">
        <u-form-item label="退料工程" prop="projectName" borderBottom required>
          <u-cell-group :border="false">
            <u-cell
              :value="formData.projectName"
              isLink
              :label="formData.projectName ? '' : '请选择退料工程'"
              :border="false"
              @click="showPicker = true"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <u-form-item label="退料日期" prop="backTime" borderBottom required>
          <u-cell-group :border="false">
            <u-cell
              isLink
              :label="formData.backTime ? '' : '请选择退料日期'"
              :value="formData.backTime"
              :border="false"
              @click="showPickerTime = true"
            ></u-cell>
          </u-cell-group>
        </u-form-item>
        <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="phone" borderBottom required>
          <u-input
            v-model="formData.phone"
            type="number"
            placeholder="请输入经办人电话"
            border="none"
            inputAlign="right"
            maxlength="11"
            @blur="handlePhone"
          ></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>

    <uni-section title="退料物资明细" type="line"></uni-section>
    <div class="cont">
      <div class="list-no" v-if="detailList.length == 0">
        <u-icon name="/static/images/no_data_icon.png" width="98" height="64"></u-icon>
        <span style="font-weight: 800; margin: 8px 0">您还没有选择退料的类型</span>
        <span style="color: #999">需要选择类型后才能进行退料</span>
        <u-button
          type="primary"
          plain
          icon="coupon-fill"
          text="选择退料类型"
          style="margin: 8px 0"
          @click="showType = true"
        ></u-button>
      </div>
      <div v-else>
        <div class="top-cont">
          <div class="top-cont-item">
            <u-input
              v-model="typeName"
              placeholder="请输入名称"
              suffixIcon="search"
              suffixIconStyle="color: #666"
              shape="circle"
              @blur="handleSearch"
            ></u-input>
          </div>
          <div class="top-cont-item">
            <u-button
              type="success"
              plain
              icon="coupon-fill"
              text="选择退料类型"
              style="margin: 8px 0"
              @click="handleShowType"
            ></u-button>
          </div>
        </div>
        <u-row justify="space-around" customStyle="margin: 10px 0;" gutter="6">
          <u-col span="2" textAlign="center">
            <div>序号</div>
          </u-col>
          <u-col span="3" textAlign="center">
            <div>名称</div>
          </u-col>
          <u-col span="4" textAlign="center">
            <div>规格</div>
          </u-col>
          <u-col span="3" textAlign="right">
            <div>
              <span style="color: red">*</span>
              退回数量
            </div>
          </u-col>
        </u-row>
        <div class="list-item" v-for="(item, index) in searchList" :key="index">
          <u-row justify="space-around" customStyle="margin-bottom: 10px;" gutter="6">
            <u-col span="2" textAlign="center">
              <div>{{ index + 1 }}</div>
            </u-col>
            <u-col span="3" textAlign="center">
              <div>{{ item.name }}</div>
            </u-col>
            <u-col span="4" textAlign="center">
              <div>{{ item.model }}</div>
            </u-col>
            <u-col span="3" textAlign="right">
              <div>
                <u-input
                  type="number"
                  placeholder="返回数量"
                  border="surround"
                  v-model="item.num"
                  @blur="handleNum(item)"
                ></u-input>
              </div>
            </u-col>
          </u-row>
        </div>
      </div>
    </div>

    <div v-if="detailList.length > 0" style="height: 60px"></div>
    <div class="bt-btn" v-if="detailList.length > 0">
      <u-button type="primary" text="保 存" style="margin: 8px 0" @click="submit"></u-button>
    </div>

    <!-- 选择器 -->
    <u-picker
      v-if="showPicker"
      :show="showPicker"
      :columns="[columns]"
      keyName="label"
      @cancel="showPicker = false"
      @confirm="confirm"
    ></u-picker>

    <!-- 日期 -->
    <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>

    <!-- 类型弹出层 -->
    <u-popup :show="showType" mode="center" :closeOnClickOverlay="false" round="8">
      <div class="uPopup">
        <div class="pop-title">选择退回的名称</div>
        <u-input
          v-model="typePopName"
          placeholder="请输入名称"
          suffixIcon="search"
          suffixIconStyle="color: #666"
          shape="circle"
          @blur="handlePopSearch"
        ></u-input>
        <!-- 列表 -->
        <div class="type-list">
          <u-row justify="space-around" customStyle="margin: 10px 0;" gutter="6">
            <u-col span="2" textAlign="center">
              <div>序号</div>
            </u-col>
            <u-col span="3" textAlign="center">
              <div>名称</div>
            </u-col>
            <u-col span="4" textAlign="center">
              <div>规格</div>
            </u-col>
            <u-col span="3" textAlign="right">
              <div>
                <span style="color: red">*</span>
                退回数量
              </div>
            </u-col>
          </u-row>
          <div class="list-item" v-for="(item, index) in inventoryPopList" :key="index">
            <u-row justify="space-around" customStyle="margin-bottom: 10px;" gutter="6">
              <u-col span="2" textAlign="center">
                <div>{{ index + 1 }}</div>
              </u-col>
              <u-col span="3" textAlign="center">
                <div>{{ item.name }}</div>
              </u-col>
              <u-col span="4" textAlign="center">
                <div>{{ item.model }}</div>
              </u-col>
              <u-col span="3" textAlign="right">
                <div>
                  <u-input
                    type="number"
                    placeholder="返回数量"
                    border="surround"
                    v-model="item.num"
                    @blur="handleNum(item)"
                  ></u-input>
                </div>
              </u-col>
            </u-row>
          </div>
        </div>

        <div style="height: 35px"></div>
        <div class="btn">
          <u-button plain text="取消" style="margin: 8px 0" @click="showType = false"></u-button>
          <u-button type="primary" plain text="确定" style="margin: 8px 0" @click="selectType"></u-button>
        </div>
      </div>
    </u-popup>

    <!-- loading -->
    <u-loading-page :loading="isLoading" icon-size="39" style="z-index: 99999"></u-loading-page>
  </view>
</template>

<script>
import config from '@/config'
import { getProList, getMaTypeByReturnCheck, addData } from '@/api/aqSafety'

export default {
  data() {
    return {
      actionUrl: config.baseUrl + config.uploadFileUrl,
      token: uni.getStorageSync('App-Token'),
      isLoading: false,
      showPicker: false,
      columns: [],
      showPickerTime: false,
      dataTime: Number(new Date()),
      showType: false, // 退料类型弹框
      formData: {
        projectName: '', // 退料工程
        projectId: '', // 退料工程id
        backTime: '', // 退料日期
        manager: '', // 经办人
        phone: '', // 经办人电话
        remark: '', // 备注
        fileList: [], // 附件
        uploadPaths: [] // 上传文件
      },
      rules: {
        projectName: [{ required: true, message: '请选择退料工程', trigger: 'change' }],
        backTime: [{ required: true, message: '请选择退料日期', trigger: 'change' }],
        manager: [{ required: true, message: '请输入经办人', trigger: 'change' }],
        phone: [{ required: true, message: '请输入经办人电话', trigger: 'change' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'change' }]
      },
      // 退料物资明细-列表
      detailList: [],
      searchList: [], // 搜索列表
      inventoryPopList: [], // 退料物资明细弹框列表
      typeName: '', // 退料物资明细-搜索名称
      typePopName: '' // 退料物资明细弹框-搜索名称
    }
  },
  onLoad() {
    this.getProList()
    this.getMaTypeByReturnCheck()
  },
  methods: {
    // 获取退料工程列表
    async getProList() {
      try {
        const res = await getProList()
        console.log('🚀 ~ getProList ~ res', res)
        this.columns = res.data.map(item => {
          return {
            label: item.name,
            value: item.id
          }
        })
      } catch (error) {
        console.log('🚀 ~ getProList ~ error', error)
      }
    },
    // 校验手机号
    handlePhone() {
      if (!/^1[3456789]\d{9}$/.test(this.formData.phone)) {
        this.$modal.msg('请输入正确的手机号')
        this.formData.phone = ''
      }
    },
    // 获取物资类型-列表
    async getMaTypeByReturnCheck() {
      try {
        const params = {
          encryptedData: JSON.stringify({ keyWord: this.typePopName }),
          pageNum: 1,
          pageSize: 9999
        }
        const res = await getMaTypeByReturnCheck(params)
        console.log('🚀 ~ getMaTypeByReturnCheck ~ res', res)
        this.inventoryPopList = res.data.list
      } catch (error) {
        console.log('🚀 ~ getMaTypeByReturnCheck ~ error', error)
      }
    },
    // 右侧文字点击事件
    handleRightText() {
      console.log('🚀 ~ handleRightText ~ ')
      uni.navigateTo({
        url: '/pages/returnInventory/returnInventoryRecord'
      })
    },
    // 日期选择器
    confirmTime(e) {
      console.log('🚀 ~ confirmTime ~ e', e)
      this.formData.backTime = this.formatTimestamp(e.value)
      console.log('🚀 ~ confirmTime ~ this.formData.backTime:', this.formData.backTime)
      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}`
    },
    // 选择器
    confirm(e) {
      console.log('🚀 ~ confirm ~ e', e)
      this.formData.projectName = e.value[0].label
      this.formData.projectId = e.value[0].value
      this.showPicker = false
    },
    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)
    },
    handleNum(item) {
      // 校验退回数量-只能是正整数
      const reg = /^[1-9]\d*$/
      if (!reg.test(item.num)) {
        this.$modal.msg('退回数量只能是正整数')
        // 去除.后面的数字
        item.num = item.num.replace(/\.\d+/, '')
      }
    },
    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)
        }
      })
    },
    handleSearch() {
      console.log('🚀 ~ handleSearch ~ ', this.typeName)
      // 前端搜索, 根据typeName搜索
      if (this.typeName == '') {
        this.searchList = this.detailList
      } else {
        this.searchList = this.detailList.filter(item => item.name.includes(this.typeName))
      }
    },
    handlePopSearch() {
      console.log('🚀 ~ handlePopSearch ~ ')
      this.getMaTypeByReturnCheck()
    },
    // 选择退料类型
    selectType() {
      console.log('🚀 ~ selectType ~ ')
      // 根据 inventoryPopList 中的 num 有值则为选择的退料类型, 将其添加到 detailList 中
      this.detailList = []
      this.inventoryPopList.forEach(item => {
        if (item.num) {
          this.detailList.push(item)
        }
      })
      this.searchList = this.detailList
      console.log('🚀 ~ selectType ~ this.detailList:', this.detailList)
      this.showType = false
    },
    // 显示退料类型弹框
    handleShowType() {
      // 如果 detailList 有值, 则回显到弹框中
      if (this.detailList.length > 0) {
        this.inventoryPopList.forEach(item => {
          this.detailList.forEach(list => {
            if (item.modelId === list.modelId) {
              item.num = list.num
            }
          })
        })
      }
      setTimeout(() => {
        this.showType = true
      }, 200)
    },
    // 提交
    submit() {
      console.log('🚀 ~ submit ~ ')
      console.log('🚀 ~ submit ~ this.formData:', this.formData)
      console.log('🚀 ~ submit ~ this.detailList:', this.detailList)
      // 校验表单
      this.$refs.uForm.validate().then(res => {
        try {
          let valid = true
          // 校验退料物资明细
          this.detailList.forEach(item => {
            if (!item.num) {
              this.$modal.msg('请填写退回数量')
              valid = false
              return
            }
          })
          if (!valid) return
          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,
                    detailList: this.detailList
                  }
                  delete params.fileList
                  console.log('🚀 ~ submit ~ params:', params)
                  const encryptedData = JSON.stringify(params)
                  const res = await addData({ encryptedData })
                  console.log('🚀 ~ submit ~ res:', res)
                  this.isLoading = false
                  this.$modal.msg('提交成功')
                  setTimeout(() => {
                    // 刷新页面
                    uni.reLaunch({
                      url: '/pages/returnInventory/index'
                    })
                  }, 200)
                } catch (error) {
                  console.log('🚀 ~ submit ~ error', error)
                  this.isLoading = false
                }
              }, 600)
            })
            .catch(error => {
              console.error('文件上传过程中出现错误:', error)
              this.isLoading = false
            })
        } catch (error) {
          console.log('🚀 ~ submit ~ error', error)
          this.isLoading = false
        }
      })
    }
  }
}
</script>

<style lang="scss">
.cont {
  padding: 0 15px;

  .list-no {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .top-cont {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 10px 0;
  }
}

.bt-btn {
  padding-bottom: 8px;
  width: calc(100% - 30px);
  background: #fff;
  // 固定底部
  position: fixed;
  bottom: 0;
  left: 15px;
}
.uPopup {
  width: 90vw;
  height: 80vh;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-sizing: border-box;
  overflow-y: auto;
  .pop-title {
    font-size: 16px;
    font-weight: 800;
    margin-bottom: 10px;
    text-align: center;
    color: #777;
  }

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