<template>
  <view class="mx3">
    <my-add-button @handleClick="openSpare" />
    <view class="main-color-bg main-bg-future"></view>
    <view class="p3 bg-color-white form-view">
      <u-form :model="form" :error-type="['message']" ref="uForm">
        <view class="main-color-text f-size-32 f-weight-6">入库信息</view>
        <!--<u-form-item label="仓库名称" prop="storeId" required label-width="150">
                    <my-select
                        :list="storeList"
                        :value-name="'id'"
                        :label-name="'name'"
                        v-model="form.storeId"
                        placeholder="请选择仓库"
                        @selected="storeSelect"
                    />
                </u-form-item>-->
        <!-- <u-form-item required prop="storeName" label="选择仓库" :label-width="150">
             <uni-data-picker style="width:100%"  placeholder="请选择" v-model="form.industryType" :localdata="industryTypeList" />
          <my-select v-model="form.storeName" label-name="title" child-name="children" :list="storeTree" mode="mutil-column-auto" placeholder="请选择仓库" @selected="industryTypeConfirm"></my-select>
        </u-form-item> -->
        <u-form-item label="备品用途" prop="type" label-width="150">
          <my-select :list="reasonList" v-model="form.type" @selected="typeSelect" placeholder="请选择备品用途" />
        </u-form-item>

        <u-form-item label="入库说明" label-width="150">
          <u-input type="textarea" v-model="form.remark" />
        </u-form-item>
      </u-form>
    </view>
    <view class="m3">
      <u-button @click="handleQrCode" shape="circle">备件扫码</u-button>
    </view>
    <view class="shop-car">
      <commonCar :list="goodsProducts" @delect="delect" ref="refCar" @accounts="accounts">

      </commonCar>
      <image src="" mode=""></image>
    </view>
  </view>
</template>

<script>
import commonCar from '@/components/shopCar/shopCar.vue'
export default {
  components: { commonCar },
  data() {
    return {
      goodsProducts: [],
      storeTree: [],
      industryTypeShow: false,
      typeMap: {},
      form: {
        storeId: '',
        type: '',
        reason: '',
        storeName: null
      },
      receiveDetailFormList: [],
      backSpareId: '',
      backSpareName: '',
      backFormName: '',
      backPrice: 0,
      isRefreshDetail: true,
      sbSpareList: [],
      storeList: [],
      reasonList: [
        {
          label: '采购入库',
          value: '1'
        },
        {
          label: '闲置入库',
          value: '2'
        },
        {
          label: '调拨入库',
          value: '3'
        },
        {
          label: '发运入库',
          value: '4'
        },
        {
          label: '盘点校准',
          value: '5'
        }
      ],
      rules: {
        type: [
          {
            required: true,
            message: '请选择入库类型',
            trigger: ['change']
          }
        ],
        storeName: [
          {
            required: true,
            message: '请选择仓库',
            trigger: ['change']
          }
        ]
      },
      detailFormRules: {
        spareId: [
          {
            required: true,
            message: '请选择备品',
            trigger: ['change']
          }
        ],
        num: [
          {
            required: true,
            message: '请填写数量',
            trigger: ['change', 'blur']
          }
        ]
      },
      id: '', // 列表 id
      aId: 0
    }
  },
  created() {
    this.typeMap = this.$DictCache.getLabelByValueMapByType(this.$DictCache.TYPE.IN_STORE_FORM_TYPE)
    this.$Http.fetchStoreTree().then(res => {
      this.storeTree = res.data
    })
  },
  onShow() {
    // 获取设备与仓库
    this.initData()
    const pages = getCurrentPages()
    const currPage = pages[pages.length - 1]

    if (currPage.goods != null && currPage.goods.length > 0) {
      currPage.goods.forEach(item => {
        console.log('item.spareId：', item.id)
        let find = false
        this.goodsProducts.forEach(spare => {
          if (spare.id === item.id) {
            find = true
            return
          }
        })
        if (!find) {
          const length = this.goodsProducts.length
          //this.goodsProducts.push(item)
          const target = { ...item }
          this.$set(this.goodsProducts, length, target)
        }
      })
      console.log(this.goodsProducts)
      currPage.goods = null
      // #ifdef MP-WEIXIN
      this.$refs.refCar.setDatas(this.goodsProducts)
      //this.$refs.refCar.statistics()
      // #endif
    }
  },
  onLoad(options) {},
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    // 刪除
    delect(e) {
      this.goodsProducts.forEach((item, index) => {
        if (item.checked === 2) {
          this.goodsProducts.splice(index, 1)
          return
        }
      })
    },
    // 提交
    accounts(e) {
      const params = { ...this.form }

      params.detailList = this.goodsProducts
      this.$Http.addInStoreForm(params).then(res => {
        uni.redirectTo({
          url: '/pages/in-store/in-store-detail?id=' + res.data.id
        })
      })
    },
    del(index) {
      console.log(this.receiveDetailFormList)
      this.receiveDetailFormList.splice(index, 1)
      console.log(this.receiveDetailFormList)
    },
    handleSelect() {
      uni.navigateTo({
        url: '/pages/search/spare-search?storeId=' + encodeURIComponent(JSON.stringify(this.form.storeId)) + '&formName=' + encodeURIComponent(JSON.stringify(formName))
      })
    },
    initData() {
      if (this.storeList.length == 0) {
        this.$Http.getStorePage({ pageNum: 1, pageSize: 1000 }).then(res => {
          this.storeList = res.data.rows
        })
      }
    },
    openSpare() {
      uni.navigateTo({
        url: '/pages/search/spare-search-goods'
      })
    },
    storeSelect(value, item) {
      this.form.storeName = item.name
      this.isRefreshDetail = true
      this.receiveDetailFormList = []
    },
    industryTypeConfirm(e) {
      console.log(e)
      this.form.storeName = e[e.length - 1].label
      this.form.storeId = e[e.length - 1].value
      console.log('this.form.storeName：' + this.form.storeName)
      this.isRefreshDetail = true
      this.receiveDetailFormList = []
    },
    typeSelect(value, item) {
      this.isRefreshDetail = true
      //this.receiveDetailFormList = []
    },
    spareSelect(value, item) {
      this.receiveDetailFormList.forEach(spare => {
        if (spare.spareId === item.spareId) {
          spare.item = item
        } else {
          console.log(2222, spare.spareId, item.id)
        }
      })
    },
    // 扫码
    handleQrCode() {
      const that = this
      // #ifdef H5
      uni.showToast({
        title: '暂不支持该功能',
        icon: 'none'
      })
      // #endif
      // #ifndef H5
      uni.scanCode({
        success(e) {
          console.log(e.result)
          if (e.result) {
            const id = e.result
            if (id != null) {
              that.$Http.fetchSparePartInfo({ id: id }).then(res => {
                var item = res.data
                let find = false
                that.goodsProducts.forEach(spare => {
                  if (spare.spareId === id) {
                    find = true
                    return
                  }
                })
                if (!find) {
                  const selectGoods = {
                    spareId: item.id,
                    image: item.image,
                    name: item.name,
                    remark: item.ggxh,
                    price: item.initialValue,
                    number: 1.0,
                    checked: 2
                  }
                  that.goodsProducts.push(selectGoods)
                  // #ifdef MP-WEIXIN
                  that.$refs.refCar.setDatas(that.goodsProducts)
                  //that.$refs.refCar.statistics()
                  // #endif
                }
              })
            } else {
              uni.showToast('非本系统二维码，无法识别')
            }
          }
        }
      })
      // #endif
    },
    // 提交
    submit() {
      if (this.form.storeName == null) {
        uni.showToast({
          title: '请选择入库仓',
          icon: 'none'
        })
        return
      }
      if (this.receiveDetailFormList == null || this.receiveDetailFormList.length === 0) {
        uni.showToast({
          title: '请添加入库明细',
          icon: 'none'
        })
        return
      }
      const promiseList = []
      promiseList.push(
        new Promise((resolve, reject) => {
          this.$refs.uForm.validate().then(valid => {
            if (valid) {
              resolve(valid)
            } else {
              reject(valid)
            }
          })
        })
      )
      this.receiveDetailFormList.forEach(item => {
        promiseList.push(
          new Promise((resolve, reject) => {
            this.$refs[item.formName][0].validate(valid => {
              if (valid) {
                resolve(valid)
              } else {
                reject(valid)
              }
            })
          })
        )
      })
      Promise.all(promiseList).then(
        res => {
          // 执行
          const params = { ...this.form }
          const detailList = []
          this.receiveDetailFormList.forEach(item => {
            const space = item.item
            const detail = {
              spareId: item.spareId,
              num: item.num,
              price: item.price,
              spareName: item.spareName,
              storeNum: item.num,
              totalPrice: this.$BaseTool.Number.mul(item.num, item.price)
            }
            detailList.push(detail)
          })
          params.detailList = detailList
          console.log(33, params)
          this.$Http.addInStoreForm(params).then(res => {
            uni.redirectTo({
              url: '/pages/out-store/out-store-detail?id=' + res.data.id
            })
          })
        },
        err => {
          console.log(err)
        }
      )
    }
  },
  onReady() {
    //this.$refs.uForm.setRules(this.rules);
  }
}
</script>

<style lang="less">
page {
  background-color: #f4f4f4;
}
.mt-3-imt {
  margin-top: 30rpx;
}
.shop-car {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f5f5f5;
}
</style>
