<template>
  <el-dialog
    :title="title + ' - ' + warehousing.orderNo"
    :visible.sync="visible"
    width="1280px"
  >
    <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
      <el-descriptions border :column="2">
        <el-descriptions-item>
          <template slot="label"><span style="color: red">*</span>{{ $t('中文品名') }}</template>
          <span style="min-width: 200px;margin-right: 15px;display: inline-block">
              {{ warehousing.prodTitleZh }}
            </span>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"><span style="color: red">*</span>{{ $t('英文品名') }}</template>
          <span>{{ warehousing.prodTitleEn }}</span>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('品牌')">
          <template slot="label"><span style="color: red">*</span>{{ $t('品牌') }}</template>
          <el-form-item required label="" prop="brand" label-width="0">
            <el-select
              v-model="form.brand"
              :placeholder="$t('可修改')"
              filterable
              remote
              @change="handleBrandChange"
              :remote-method="getProductBrandPage"
              disabled>
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.titleZh"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-descriptions-item>
        <el-descriptions-item :label="$t('是否备案')">
          <template slot="label"><span style="color: red">*</span>{{ $t('是否备案') }}</template>
          {{ isBeian }}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('收费模式')">
          <template slot="label"><span style="color: red">*</span>{{ $t('收费模式') }}</template>
          {{ feeType }}
        </el-descriptions-item>
        <el-descriptions-item :label="$t('填单参数')">
          {{ $t('箱数：') }}<span>{{ warehousing.num }}</span><br>
          {{ $t('体积：') }}<span>{{ warehousing.volume }}</span>m³<br>
          {{ $t('重量：') }}<span>{{ warehousing.weight }}</span>Kg
        </el-descriptions-item>
      </el-descriptions>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="$t('材质')" style="margin-top: 20px">
            <dict-tag :type="DICT_TYPE.ECW_PRODUCT_MATERIAL" :value="orderItemB.material" clearable></dict-tag>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item :label="$t('入仓特性')" style="margin-top: 20px">
            <el-checkbox-group v-model="form.prodAttrIds" disabled>
              <el-checkbox v-for="item in attrList" :key="item.id" :label="item.id">{{ item.attrName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <!--<el-form-item :label="$t('入仓时间')" v-if="!edit">
        {{form.inTime}}
      </el-form-item>-->
    </el-form>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('入仓记录') }}</span>
        <el-button style="float: right;margin-left: 15px" size="mini" type="primary" icon="el-icon-minus" circle @click="handleDelete" :disabled="form.table.length < protectRowCount"></el-button>
        <el-button style="float: right" size="mini" type="primary" icon="el-icon-plus" circle @click="handleAdd()"></el-button>
      </div>
      <el-form ref="tableForm" :rules="tableFormRules" :model="form" size="mini">
        <el-table
          :data="form.table"
          style="width: 100%">
          <el-table-column :label="$t('箱数')" width="150px">
            <template v-slot:header>
              <span style="color: red">*</span>{{ $t('箱数') }}</template>
            <template v-slot="{r,c,$index}">
              <el-form-item :rules="tableFormRules.cartonsNum">
                <el-input v-model="form.table[$index].cartonsNum" placeholder="" @blur="handleVolume($index)" :disabled="$index < protectRowCount">
                  <span slot="append">{{ getDictDataLabel(DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE, form.table[$index].specificationType) }}</span>
                </el-input>
                <dict-selector :disabled="$index < protectRowCount" :type="DICT_TYPE.WAREHOUSING_SPECIFICATION_TYPE" v-model="form.table[$index].specificationType" @change="handleVolume($index)"></dict-selector>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('包装类型')" width="100px">
            <template v-slot:header>
              <span style="color: red">*</span>{{ $t('包装类型') }}</template>
            <template v-slot="{r,c,$index}">
              <el-form-item>
                <dict-selector :disabled="$index < protectRowCount" :type="DICT_TYPE.ECW_PACKAGING_TYPE" v-model="form.table[$index].unit"></dict-selector>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="长(cm)">
            <template v-slot:header>
              <span>{{ $t('长') }}</span>(cm)
            </template>
            <template v-slot="{r,c,$index}">
              <el-form-item :rules="tableFormRules.boxGauge1">
                <el-input :disabled="$index < protectRowCount" type="number" v-model="form.table[$index].boxGauge1" placeholder="" @blur="handleVolume($index)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="宽(cm)">
            <template v-slot:header>
              <span>{{ $t('宽') }}</span>(cm)
            </template>
            <template v-slot="{r,c,$index}">
              <el-form-item :rules="tableFormRules.boxGauge2">
                <el-input :disabled="$index < protectRowCount" type="number" v-model="form.table[$index].boxGauge2" placeholder="" @blur="handleVolume($index)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="高(cm)">
            <template v-slot:header>
              <span>{{ $t('高') }}</span>(cm)
            </template>
            <template v-slot="{r,c,$index}">
              <el-form-item :rules="tableFormRules.boxGauge3">
                <el-input :disabled="$index < protectRowCount" type="number" v-model="form.table[$index].boxGauge3" placeholder="" @blur="handleVolume($index)"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="体积(m³)">
            <template v-slot:header>
              <span style="color: red">*</span> <span>{{ $t('体积') }}</span>(m³)
            </template>
            <template v-slot="{r,c,$index}">
              <el-form-item :rules="tableFormRules.volume">
                <el-input :disabled="$index < protectRowCount" v-model="form.table[$index].volume" placeholder="" type="number"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="重量(Kg)">
            <template v-slot:header>
              <span style="color: red">*</span> <span>{{ $t('重量') }}</span>(Kg)
            </template>
            <template v-slot="{r,c,$index}">
              <el-form-item :rules="tableFormRules.weight">
                <el-input :disabled="$index < protectRowCount" v-model="form.table[$index].weight" placeholder="" type="number"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('数量')" width="130px">
            <template v-slot="{r,c,$index}">
              <el-form-item :rules="tableFormRules.quantityAll">
                <el-input :disabled="$index < protectRowCount" v-model.number="form.table[$index].quantityAll" placeholder="">
                  <template slot="append">{{ $t('个') }}</template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('快递单号')">
            <template v-slot="{r,c,$index}">
              <el-form-item>
                <el-input :disabled="$index < protectRowCount" v-model="form.table[$index].expressNo" placeholder=""></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('储位')" prop="orderLocationBackVOList"  width="150px">
            <template v-slot="{ row, column, $index }">
              <warehouse-area-select
                v-if="visible"
                v-model="form.table[$index].orderLocationBackVOList"
                :order-id="orderId"
                :order-item-id="warehousing.orderItemId"
                :warehouse-in-id="form.table[$index].id"
                :warehouse-id="warehouseId"
                :is-editing="edit"></warehouse-area-select>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')">
            <template v-slot="{ row, column, $index}">
              <el-popconfirm
                v-if="$index >= protectRowCount"
                title="确定要删除该行记录吗？"
                @confirm="handleDeleteRow($index)"
              >
                <template v-slot:reference>
                  <el-button size="mini" type="danger">{{$t('删除')}}</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-card>

    <span slot="footer">
        <el-button type="primary" @click="handleSubmit">{{ $t('完成打包') }}</el-button>
        <el-button @click="handleClose">{{ $t('返回')}}</el-button>
      </span>
  </el-dialog>
</template>

<script>
import ProductSelector from "@/components/ProductSelector"
import WarehouseAreaSelect from "@/components/WarehouseAreaSelect"
import {getFeeTypeByOrderProduct, getProductBrankPage} from "@/api/ecw/productBrank"
import {cancelProcessInstance} from "@/api/bpm/processInstance"
import WorkFlow from "@/components/WorkFlow"
import {DICT_TYPE, getDictDataLabel, getDictDatas} from "@/utils/dict"
import {finishPacked, orderWarehouseIn, orderWarehouseInUpdateApply} from "@/api/ecw/order"
import {getProductAttrList} from "@/api/ecw/productAttr"
import {getProductTypeList} from "@/api/ecw/productType"
import {addProduct} from "@/api/ecw/product"

export default {
  name: "Package",

  components: {
    ProductSelector,
    WarehouseAreaSelect,
    WorkFlow
  },

  props: {
    title: {
      type: String,
      default: undefined
    },
    order: {
      type: Object,
      default: undefined
    },
    // 是否集运
    isJiyun: {
      type: Boolean,
      default: false
    },
    // 是否修改
    edit: {
      type: Boolean,
      default: false
    },
    // 订单信息中的商品项
    orderItemA: {
      type: Object,
      default: () => {
        return {
          material: undefined,
          inTime: undefined,
          orderWarehouseInBackItemDoList: []
        }
      }
    },
    // 入仓的商品项
    orderItemB: {
      type: Object,
      default: () => {
        return {
          material: undefined,
          inTime: undefined,
          orderWarehouseInBackItemDoList: []
        }
      }
    }
  },

  mounted() {
    this.getAttrList()
    this.getTypeList()
  },

  computed: {
    isAdd() {
      return this.$route.path === "/order/warehousing-add"
    },
    warehousing(){
      return {...this.orderItemA, ...this.orderItemB}
    },
    orderId(){
      return this.order.orderId
    },
    brandObject(){
      return this.brandList.find(e => e.id === this.form.brand) || ''
    },
    brandObject1(){
      return this.brandList.find(e => e.id === this.form1.brand) || ''
    },
    isBeian(){
      if (this.form.recordMode !== undefined){
        return [this.$t('无备案'), this.$t('有备案'), this.$t('中性')][this.form.recordMode]
      }
      if (this.brandObject.filing){
        return [this.$t('无备案'), this.$t('有备案'), this.$t('中性')][this.brandObject.filing]
      } else {
        return ''
      }
    },
    isBeian1(){
      if (this.form1.recordMode !== undefined){
        return [this.$t('无备案'), this.$t('有备案'), this.$t('中性')][this.form1.recordMode]
      }
      if (this.brandObject1.filing){
        return [this.$t('无备案'), this.$t('有备案'), this.$t('中性')][this.brandObject1.filing]
      } else {
        return ''
      }
    },
    /**
     * 收费模式
     * @returns {string} 无牌价0，有牌价1，中性品牌价2
     */
    feeType(){
      const feeType = this.form.feeType
      if (feeType >= 0 && feeType < 3) {
        return [this.$t('无牌价'), this.$t('有牌价'), this.$t('中性品牌价')][feeType]
      }
      return ''
    },
    feeType1(){
      const feeType = parseInt(this.form1.feeType)
      if (feeType >= 0 && feeType < 3) {
        return [this.$t('无牌价'), this.$t('有牌价'), this.$t('中性品牌价')][feeType]
      }
      return ''
    },
    warehouseId(){
      return this.order.adjustToDestWarehouseId || this.order?.logisticsInfoDto?.startWarehouseId
    }
  },

  watch: {
    visible(val){
      if (val) {
        this.init()
        this.getProductBrandPage(this.warehousing.brandName)
        this.getProductBrandPage1()
        this.handleBrandChange(parseInt(this.form.brand))
      } else {
        this.$emit('close')
      }
    }
  },

  data(){
    return {
      DICT_TYPE,
      getDictDataLabel,
      getDictDatas,
      activeName: 'first',
      visible: false,
      form: {
        table: [],
        brandType: undefined,
        orderId: undefined,
        orderNo: undefined,
        brand: undefined,
        inTime: undefined,
        material: undefined,
        orderItemId: undefined,
        prodAttrIds: [],
        prodId: undefined,
        prodTitleEn: undefined,
        prodTitleZh: undefined,
        prodType: undefined,
        type: undefined,
        feeType: undefined,
        recordMode: undefined
      },
      form1: {
        table: [],
        brandType: undefined,
        orderId: undefined,
        orderNo: undefined,
        brand: undefined,
        inTime: undefined,
        material: undefined,
        orderItemId: undefined,
        prodAttrIds: [],
        prodId: undefined,
        prodTitleEn: undefined,
        prodTitleZh: undefined,
        prodType: undefined,
        type: 1,
        feeType: undefined,
        recordMode: undefined
      },
      brandList: [],
      brandList1: [],
      formRules: {
        prodId: [{required: true, message: this.$t("请选择品名"), trigger: "change"}],
        brand: [{required: true, message: this.$t("请选择品牌"), trigger: "change"}],
      },
      tableFormRules: {
        // cartonsNum: [{required: true, message: this.$t("箱数不能为空"), trigger: "change"}],
        // boxGauge1: [{required: true, message: this.$t("货物长不能为空"), trigger: "change"}],
        // boxGauge2: [{required: true, message: this.$t("货物宽不能为空"), trigger: "change"}],
        // boxGauge3: [{required: true, message: this.$t("货物高不能为空"), trigger: "change"}],
        // volume: [{required: true, message: this.$t("体积不能为空"), trigger: "change"}],
        // weight: [{required: true, message: this.$t("重量不能为空"), trigger: "change"}],
        // // quantityAll: [{required: true, message: this.$t("数量不能为空"), trigger: "change"}]
      },


      selectedUsers: undefined,

      // 入仓修改正在审核中
      isEditing: false,
      // 审批业务id
      formId: '',

      // 追加时被保护的行数
      protectRowCount: -1,

      // 添加商品弹窗
      isShowProduct: false,
      productForm: {
        typeId: undefined,
        attrArray: [],
        titleZh: undefined,
        titleEn: undefined
      },
      productRules: {
        typeId: [{ required: true, message: this.$t("商品类型不能为空"), trigger: "change" }],
        // attrArray: [{ required: true, message: this.$t("商品特性不能为空"), trigger: "change" }],
        titleZh: [{ required: true, message: this.$t("中文标题不能为空"), trigger: "blur" }],
        titleEn: [{ required: true, message: this.$t("英文标题不能为空"), trigger: "blur" }],
      },
      //类型列表
      typeList: [],
      // 特性列表
      attrList: []
    }
  },
  created() {
    this.visible = true
  },
  methods: {
    init(){
      this.form.brandType = this.warehousing.brandType
      this.form.orderId = this.warehousing.orderId
      this.form.orderItemId = this.warehousing.orderNo
      this.form.orderNo = this.warehousing.orderNo
      this.form.brand = this.warehousing.brand
      this.form.brandType = this.warehousing.brandType
      this.form.inTime = this.warehousing.inTime
      this.form.material = this.warehousing.material
      this.form.orderId = this.warehousing.orderId
      this.form.orderItemId = this.warehousing.orderItemId
      this.form.orderNo = this.warehousing.orderNo
      this.form.prodAttrIds = this.warehousing.prodAttrIds?.split(',').map(e => +e) || []
      this.form.prodId = this.warehousing.prodId
      this.form.prodTitleEn = this.warehousing.prodTitleEn
      this.form.prodTitleZh = this.warehousing.prodTitleZh
      this.form.prodType = this.warehousing.prodType
      this.form.type = this.warehousing.type
      this.form.feeType = this.warehousing.feeType

      this.warehousing.orderWarehouseInBackItemDoList.forEach(e => {
        let bg = {}
        if (e.boxGauge) {
          const boxGauge = e.boxGauge.split('*')
          // e.boxGauge1 = boxGauge[0]
          // e.boxGauge2 = boxGauge[1]
          // e.boxGauge3 = boxGauge[2]
          bg = {
            boxGauge1: boxGauge[0],
            boxGauge2: boxGauge[1],
            boxGauge3: boxGauge[2]
          }
        }
        this.form.table.push({...e, ...bg})
      })

      if (!this.edit){
        let protectRowCount = 0
        this.protectRowCount = this.form.table.map(e => {
          if (e.id){
            protectRowCount++
          }
        })
        this.protectRowCount = protectRowCount
        this.handleAdd()
        this.handleAdd(1)
      }
    },
    handleClose() {
      this.visible = false
    },
    handleVolume(index, val){
      setTimeout(() => {
        const {boxGauge1, boxGauge2, boxGauge3, specificationType, cartonsNum} = (val === 1 ? this.form1.table : this.form.table)[index]
        let result = ''
        if (boxGauge1 && boxGauge2 && boxGauge3 && specificationType && cartonsNum) {
          result = (((specificationType === 1 || specificationType === '1') ? cartonsNum : 1) * (boxGauge1 * boxGauge2 * boxGauge3) / 1000000 + 0.000001)?.toFixed(2) || ''
        } else {
          result = ''
        }
        if (result === '0.00') result = '0.01';
        (val === 1 ? this.form1.table : this.form.table)[index].volume = result
      }, 0)
    },
    handleSubmit() {
      if (this.form.prodAttrIds.indexOf(4) !== -1) {
        return this.$notify({
          title: this.$t('提示'),
          message: this.$t("订单包含不接受货物，请检查"),
          type: 'warning'
        })
      }
      this.$refs['form'].validate(valid => {
        this.$refs['tableForm'].validate(valid1 => {
          if (!valid || !valid1) {
            return
          }
          // 首次入仓、入仓补充
          return finishPacked({
            orderId: this.warehousing.orderId,
            orderItemId: this.warehousing.orderItemId,
            orderWarehouseInItemDtoList: this.form.table.map(e => {
              return {
                ...e,
                boxGauge: e.boxGauge1 + '*' + e.boxGauge2 + '*' + e.boxGauge3,
                orderLocationCreateReqVOList: e.orderLocationBackVOList
              }
            }),
          }).then(r => {
            if (r.data) {
              this.$message.success('打包成功')
              this.handleClose()
            } else {
              this.$message.success('打包失败')
            }
          })
        })
      })
    },
    handleCancelProcessInstance(){
      this.$prompt('请输入取消原因？', this.$t("取消流程"), {
        type: 'warning',
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        inputPattern: /^[\s\S]*.*\S[\s\S]*$/, // 判断非空，且非空格
        inputErrorMessage: this.$t("取消原因不能为空"),
      }).then(({ value }) => {
        cancelProcessInstance(this.formId, value).then(() => {
          this.opened = false
          this.$modal.msgSuccess("取消成功");
        })
      })
    },
    onProductChange(product){
      this.form.prodTitleZh = product.titleZh
      this.form.prodTitleEn = product.titleEn
      this.handleBrandChange(parseInt(this.form.brand))
      this.form.prodAttrIds = product.attrId ? product.attrId.split(',').map(e => +e) : []
    },
    onProductChange1(product){
      this.form1.prodTitleZh = product.titleZh
      this.form1.prodTitleEn = product.titleEn
      this.handleBrandChange(parseInt(this.form1.brand))
      this.form1.prodAttrIds = product.attrId ? product.attrId.split(',').map(e => +e) : []
    },
    getProductBrandPage(titleZh = undefined) {
      getProductBrankPage({pageSize: 20, titleZh}).then(r => {
        this.brandList = r.data.list
      })
    },
    getProductBrandPage1(titleZh = undefined) {
      getProductBrankPage({pageSize: 20, titleZh}).then(r => {
        this.brandList1 = r.data.list
      })
    },
    handleBrandChange(v){
      getFeeTypeByOrderProduct({
        brandId: parseInt(v),
        productId: this.warehousing.prodId,
        orderId: this.orderId
      }).then(r => {
        if(r.code === 0){
          (this.activeName === "first" ? this.form : this.form1).feeType = parseInt(r.data.feeType);
          (this.activeName === "first" ? this.form : this.form1).recordMode = parseInt(r.data.recordMode)
        }
      })
    },
    handleDelete(val) {
      if (val === 1) {
        this.form1.table.pop()
      } else if (this.form.table.length > this.protectRowCount) {
        this.form.table.pop()
      }
    },
    handleDeleteRow(index, val) {
      if (val === 1) {
        this.form1.table.splice(index, 1)
      } else if (this.form.table.length > this.protectRowCount) {
        this.form.table.splice(index, 1)
      }
    },
    handleAdd(val = 0) {
      let cartonsNum = ''
      if (val !== 1) { // 货物入仓
        let hasCartonsNum = 0
        this.form.table.forEach(e => {
          hasCartonsNum += e.cartonsNum
        })
        cartonsNum = this.warehousing.num - hasCartonsNum
      }

      const form = val === 1 ? this.form1 : this.form
      const formLength = form.table.length
      let orderLocationBackVOList = []
      /* // 不默认使用上一条记录的储位 https://zentao.test.jdshangmen.com/bug-view-3344.html
      if (formLength > 0) {
        orderLocationBackVOList = JSON.parse(JSON.stringify(form.table[formLength - 1].orderLocationBackVOList))
      }*/
      form.table.push({
        "boxGauge1": this.isJiyun ? 0 : '',
        "boxGauge2": this.isJiyun ? 0 : '',
        "boxGauge3": this.isJiyun ? 0 : '',
        "cartonsNum": cartonsNum > 0 ? cartonsNum : '',
        "expressNo": "",
        "quantityAll": undefined,
        "unit": "1",
        "volume": '',
        "weight": '',
        specificationType: '1',
        table: [],
        orderLocationBackVOList
      })
    },
    /** 获取产品属性列表 */
    getAttrList() {
      getProductAttrList().then(response => {
        this.attrList = response.data;
      })
    },
    /** 获取产品类型列表 */
    getTypeList() {
      getProductTypeList().then(response => {
        this.typeList = response.data;
      })
    },
    productSubmit(){
      this.$refs["productForm"].validate(valid => {
        if (!valid) {
          return;
        }
        //商品特性转字符串
        this.productForm.attrId = this.productForm.attrArray.join(',')
        // 添加的提交
        addProduct(this.productForm).then(response => {
          this.$modal.msgSuccess(this.$t("新增成功"))
          if (this.activeName === 'first') {
            this.form.prodId = response.data
            this.form.prodAttrIds = this.productForm.attrArray
          } else {
            this.form1.prodId = response.data
            this.form1.prodAttrIds = this.productForm.attrArray
          }
          this.productCancel()
        })
      })
    },
    productCancel(){
      this.isShowProduct = false
      this.productForm = {
        typeId: undefined,
        attrArray: [],
        titleZh: undefined,
        titleEn: undefined
      }
    }
  }
}
</script>

<style scoped>

</style>
