<template>
  <div style="display: inline-block">
    <template v-if="text">
      <el-button size="mini" type="text" style="margin-right: 10px" @click="handleOpen">{{ num }}（{{$t('混箱')}}}）</el-button>
    </template>
    <template v-else>
      <el-button size="mini" type="primary" style="margin-right: 10px" @click="handleOpen">{{ title }}</el-button>
    </template>
    <el-dialog
      append-to-body
      :title="title"
      :visible.sync="dialogVisible"
      width="1024px"
      :before-close="handleClose">
        <template v-slot:title>
          <div class="flex flex-items-center">
            <div class="title flex-1 flex flex-items-center">{{title}}</div>
            <el-button v-if="showChooseOrderItem" type="primary" size="mini" @click="handleShowChooseDialog">{{$t('选择订单商品')}}</el-button>
            <div style="width: 100px"><!--占位，防止被关闭按钮挡住--></div>
          </div>
        </template>

      <el-form v-if="dialogVisible">
        <WarehouseRecordDetailItem
            v-for="(item, index) in dataList"
            :key="index" v-model="dataList[index]"
            :index="index" :attr-list="attrList"
            @handle-delete="handleDelete(index)"
            :readonly="readonly"
        />
      </el-form>

      <el-button v-show="!readonly" type="primary" size="mini" @click="handleAddItem">{{$t('添加一条明细')}}</el-button>

      <span v-show="!readonly" slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t('取消')}}</el-button>
        <el-button type="primary" @click="handleSave">{{$t('确定')}}</el-button>
      </span>
    </el-dialog>
    <choose-order-products
      v-if="showChooseDialog"
      :order-id="orderId"
      :warehouse-in-id="warehouseInId"
      @close="showChooseDialog=false"
      @success="handleChooseOrderProducts"></choose-order-products>
  </div>
</template>

<script>
import ProductSelector from "@/components/ProductSelector/index.vue";
import WarehouseRecordDetailItem from "@/views/ecw/order/warehousing/components/WarehouseRecordDetailItem.vue";
import {getProductAttrList} from "@/api/ecw/productAttr";
import {getOrderItemCommonAttr} from "@/api/ecw/order";
import ChooseOrderProducts from "@/views/ecw/order/stocking/components/ChooseOrderProducts.vue";

/**
 * 入仓明细弹窗
 */
export default {
  name: 'WarehouseRecordDetail',
  components: {ChooseOrderProducts, WarehouseRecordDetailItem, ProductSelector},

  props: {
    value: {
      type: Array,
      default: () => []
    },
    readonly: {
      type: Boolean,
      default: false
    },
    text: {
      type: Boolean,
      default: false
    },
    num:{
      type:Number,
      default:0
    },
    // 是否显示添加订单商品按钮
    showChooseOrderItem:Boolean,
    orderId: Number,
    warehouseInId: Number
  },

  data() {
    return {
      dialogVisible: false,
      dataList: [],
      // 特性列表
      attrList: [],
      showChooseDialog: false
    };
  },

  mounted() {
    this.getAttrList()
  },

  methods: {
    init() {
      if (!this.value || this.value.length === 0) {
        this.dataList = [{
          "boxGauge": "",
          "brand": undefined,
          "cartonsNum": undefined,
          "createTime": "",
          "expressNo": "",
          "prodAttrIds": '',
          "prodId": undefined,
          "quantityAll": undefined,
          "specificationType": undefined,
          "unit": "",
          "usageIds": "",
          "volume": undefined,
          "weight": undefined,
          "material": undefined
        }]
      } else {
        this.dataList = JSON.parse(JSON.stringify(this.value))
      }
    },
    /** 获取产品属性列表 */
    getAttrList() {
      getProductAttrList().then(response => {
        this.attrList = response.data;
      })
    },
    handleAddItem() {
      this.dataList.push({
        "boxGauge": "",
        "brand": undefined,
        "cartonsNum": undefined,
        "createTime": "",
        "expressNo": "",
        "prodAttrIds": '',
        "prodId": undefined,
        "quantityAll": undefined,
        "specificationType": undefined,
        "unit": "",
        "usageIds": "",
        "volume": undefined,
        "weight": undefined,
        "material": undefined
      })
    },
    handleDelete(index) {
      this.dataList.splice(index, 1)
    },
    handleOpen() {
      this.init()
      this.dialogVisible = true
    },
    handleClose(done) {
      if (this.readonly) {
        return done()
      }
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    handleSave() {
      for (let i = 0; i < this.dataList.length; i++) {
        if (!this.dataList[i].prodId) {
          return this.$notify({
            title: this.$t("填写第{n}条明细的品名", {n: i=1}),
            type: "warning"
          })
        }
        if (!this.dataList[i].brand) {
          return this.$notify({
            title: this.$t("填写第{n}条明细的品牌", {n: i=1}),
            type: "warning"
          })
        }
        if(!this.dataList[i].quantityAll){
            return this.$notify({
                title: this.$t("填写第{n}条明细的数量", {n: i=1}),
                type: "warning"
            })
        }
      }
      this.$emit('input', this.dataList)
      this.dialogVisible = false
    },
    handleShowChooseDialog(){
      this.showChooseDialog = true
    },
    handleChooseOrderProducts(data){
      this.showChooseDialog = false
      if(!data?.length) return
      // 如果最后一条是空的，则删除先
      if(this.dataList?.length){
        const index = this.dataList.length - 1
        let lastItem = this.dataList[index]
        if(!lastItem.prodId && !lastItem.brand && !lastItem.prodAttrIds && !lastItem.material && !lastItem.quantityAll){
          this.dataList.splice(index, 1)
        }
      }

      data.forEach(item => {
        this.dataList.push({
          "boxGauge": "",
          "brand": item.brand,
          "cartonsNum": undefined,
          "createTime": "",
          "expressNo": "",
          "prodAttrIds": item.prodAttrIds,
          "prodId": item.prodId,
          "quantityAll": item.quantityAll,
          "specificationType": undefined,
          "unit": "",
          "usageIds": item.usageIds || "",
          "volume": undefined,
          "weight": undefined,
          "material": item.material
        })
      })
    }
  },

  computed: {
    title() {
      if (this.readonly) {
        return this.$t('查看箱明细')
      }
      return !this.value || this.value.length === 0 ? this.$t('添加箱明细') : this.$t('编辑箱明细')
    }
  }
}
</script>

<style scoped lang="scss">
.title{
  font-size: 16px;
}
</style>
