<template>
  <view style="background: #fff; min-height: calc(100vh - 44px)">
    <!-- 自定义表单校验 -->
    <uni-forms ref="form" :rules="rules" :modelValue="form" label-width="100" class="padding-xs">
      <uni-forms-item :label="$t('集运仓库')" required name="warehouseId">
        <uni-data-checkbox v-model="form.warehouseId" :localdata="warehouseList" mode="tag"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item label="快递单号" required name="expressNo">
        <uni-easyinput placeholder="请输入快递单号" v-model="form.expressNo"/>
      </uni-forms-item>
      <uni-forms-item label="快递公司">
        <uni-data-select v-model="form.expressId" :localdata="expressList" :clear="false"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item label="货运方式" class="align-center">
        <uni-data-checkbox v-model="form.transportId" :localdata="transportList"></uni-data-checkbox>
      </uni-forms-item>
      <uni-row class="padding-xs" v-for="(item,index) in consItemVOList">
        <uni-col :span="3">
          <uni-forms-item :label="'商品'+(index + 1)" class="align-center"/>
        </uni-col>
        <uni-col :span="8">
          <view @click="tagIndex(index)">
            <select-combox
                :productListToBeDetermined="productListToBeDetermined"
                :candidates="productListZh"
                @getValue="getValue"
                @input="handleInputZh"
                :modelValue="item.titleZh"
                v-model="item.titleZh"
            ></select-combox>
          </view>
        </uni-col>
        <uni-col :span="3">
          <uni-forms-item :label="'数量'+(index + 1)" class="align-center margin-left-xs"/>
        </uni-col>
        <uni-col :span="5">
          <uni-easyinput type="number" v-model="item.quantity" :clearable="false"/>
        </uni-col>
        <uni-col :span="5">
          <button class="margin-left-xs" type="warn" size="mini" @click="delProduct(index)">{{ $t('删除') }}</button>
        </uni-col>
      </uni-row>
      <button class="margin-left-xs" type="primary" size="mini" @click="addProduct()">
        {{ $t('添加') }}
      </button>
      <uni-forms-item label="填单数据" class="align-center">
        {{ sum }}个
      </uni-forms-item>
      <uni-forms-item label="订单总货值（元）" class="align-center" type="number">
        <uni-easyinput v-model="form.worth"/>
      </uni-forms-item>
      <uni-forms-item label="备注" class="align-center">
        <uni-easyinput type="textarea" v-model="form.remarks"/>
      </uni-forms-item>
    </uni-forms>

    <uni-row class="padding-xl">
      <uni-col :span="8">
        <button type="primary" size="mini" @click="submit('form')">{{ $t('确认添加') }}</button>
      </uni-col>
      <uni-col :span="8">
        <button type="primary" style="color:#ffffff;backgroundColor:#f59a23;" size="mini">
          {{ $t('入仓须知') }}
        </button>
      </uni-col>
      <uni-col :span="8">
        <button type="warn" size="mini">{{ $t('禁运物品') }}</button>
      </uni-col>
    </uni-row>

    <view class="cu-modal" :class="consModel ? 'show' : ''" style="z-index: 999;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">提示</view>
        </view>
        <view class="padding-xl">
          货值需大于等于10,请检查
        </view>
        <view class="cu-bar bg-white justify-end">
          <view class="action">
            <button class="cu-btn bg-blue margin-left" @tap="submitModel('form')">忽略,继续提交</button>
            <button class="cu-btn bg-grey margin-left" @tap="consModel=!consModel">前去检查</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>

import {createCons, getConsWarehouseApp, getExpressApp} from "@/api/cons";
import {DICT_TYPE, getDictDatas} from "@/util/dict";
import {getProductList} from "@/pages/warehousing/api";
import selectCombox from "@/components/select-combox/select-combox.vue";

export default {
  name: "create-cons",
  components: {selectCombox},
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    },
    sum() {
      let sum = 0
      for (let i in this.consItemVOList) {
        sum = sum + this.consItemVOList[i].quantity * 1
      }
      return sum
    }
  },
  data() {
    return {
      range: [{"value": 0, "text": "义乌仓"}, {"value": 1, "text": "佛山仓"}],
      // 自定义表单数据
      form: {},
      // 自定义表单校验规则
      rules: {
        expressNo: {
          rules: [{
            required: true,
            errorMessage: '快递单号不能为空'
          }]
        },
        warehouseId: {
          rules: [{
            required: true,
            errorMessage: '集运仓库不能为空'
          }]
        },
      },
      consItemVOList: [],
      warehouseList: [],
      transportList: [],
      expressList: [],
      productListZh: [],
      productListZhObj: [],
      productListEn: [],
      // 是否待确定
      productListToBeDetermined: [],
      productIndex: null,
      consModel: false
    };
  },
  onLoad: function (option) {
    const that = this
    setTimeout(function () {
      var transportList = getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE)
      for (let i in transportList) {
        that.transportList.push({value: transportList[i].value, text: transportList[i].label})
      }
    }, 100)

    getConsWarehouseApp().then(row => {
      this.warehouseList = row
      if (row) {
        this.form.warehouseId = row[0].value
      }
    })
    getExpressApp().then(row => {
      this.expressList = row
    })
    this.getProductList();
  },
  methods: {
    tagIndex(index) {
      console.log(index)
      this.productIndex = index
    },
    getValue(e) {
      if (e) {
        var sindex = 0
        const that = this
        that.productListZhObj.forEach((item, index) => {
          if (item.titleZh == e) {
            sindex = index
          }
        })
        this.consItemVOList[this.productIndex].prodId = that.productListZhObj[sindex].id
      }
    },
    getProductList(titleZh = '') {
      // 注意：由于接口特性，中英文均都必须使用titleZh字段搜索
      return getProductList({
        filter: false,
        pageSize: 30,
        titleZh
      }).then(data => {
        this.productListZh = data.list.map(v => v.titleZh)
        this.productListZhObj = data.list
        this.productListEn = data.list.map(v => v.titleEn)
        this.productListToBeDetermined = data.list.map(v => v.auditStatus !== 2)
      })
    },
    handleInputZh(e) {
      this.getProductList(e)
    },
    submit(ref) {
      this.$refs[ref].validate().then(res => {
        for (let i in this.consItemVOList) {
          if (this.consItemVOList[i].prodId === 0) {
            uni.showToast({
              title: `请选择第${1 * i + 1}个商品`,
              icon: 'none'
            })
            return
          }
        }
        if (this.form.worth === undefined || this.form.worth < 10) {
          this.consModel = true
          return;
        }
        var form = {
          ...this.form,
          consItemVOList: this.consItemVOList
        }
        createCons(form).then(() => {
          uni.redirectTo({
            url: '/pages/cons/list'
          })
        })
      }).catch(err => {
        console.log('err', err);
      })
    },
    submitModel(ref) {
      this.consModel = false
      this.$refs[ref].validate().then(res => {
        for (let i in this.consItemVOList) {
          if (this.consItemVOList[i].prodId === 0) {
            uni.showToast({
              title: `请选择第${1 * i + 1}个商品`,
              icon: 'none'
            })
            return
          }
        }
        var form = {
          ...this.form,
          consItemVOList: this.consItemVOList
        }
        createCons(form).then(() => {
          uni.redirectTo({
            url: '/pages/cons/list'
          })
        })
      }).catch(err => {
        console.log('err', err);
      })
    },
    delProduct(index) {
      this.consItemVOList.splice(index, 1)
    },
    addProduct() {
      this.consItemVOList.push({prodId: 0, titleZh: "", quantity: 1})
    }
  }
};
</script>

<style lang="scss" scoped>
.search-header {
  ::v-deep .uni-easyinput__content {
    border-radius: 20px;
    padding-right: 10px;
    background: rgba($color: #fff, $alpha: 0.5) !important;
    border: none;
    // opacity: 0.5;
  }

  ::v-deep .uni-input-placeholder {
    padding-left: 8px;
    color: #b2c9f3;
  }

  ::v-deep .uni-input-input {
    padding-left: 8px;
  }
}

.scroll {
  margin-top: -8px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  padding: 8px;
  background: #fff;

  .list-row {
    display: flex;
    align-items: center;
    // line-height: 24px;
    padding: 8px 0;

    view {
      flex: 1;
      text-align: center;
    }
  }

  .list-header {
    font-weight: bold;
  }

  .row-bg {
    background: #ebebed;
  }

  // .red-badge-wrap{
  //   position: absolute;
  //   right: -34upx;
  //   top: -26upx;
  // }
  .red-badge {
    display: inline-block;
    // background-color: #dd514c;
    color: #d9001c;
    // font-size: 24upx;
    // width: 30upx;
    // height: 30upx;
    // line-height: 30upx;
    // vertical-align: middle;
    // border-radius: 30upx;
    // margin-left: 2upx;
    /* transform: scale(0.9); */
  }
}
</style>
