<template>
  <vxe-modal v-model="value" id="editProductModal" width="70%" height="80%" @hide="hide" title="商品编辑" transfer show-footer v-loading="load">
    <by-form :propConfig="form" ref="form" @formChange="formChange">
      <template v-slot:isPay="{value}">
        <el-switch
          v-model="value.isPay">
        </el-switch>
      </template>
      <template v-slot:freeAmount="{value}">
        <vxe-input v-model="value.freeAmount" class="freeAmount" placeholder="保留两位小数或百分比输入" size="mini" @change="freeAmountChange"></vxe-input>
      </template>
    </by-form>
    <div class="tool-comp">
      <by-tool :propConfig="toolConfig" ref="tool"></by-tool>
    </div>
    <by-table :propConfig="tableConfig" ref="table">
      <template v-slot:name='{ row }'>
        <div class="product-cont">
          <div class="product-name">
            {{ row.name }}
            <el-tag v-if="row.isGift == 1" size="mini" type="success">赠</el-tag>
            <el-tag v-if="row.__status === 'delete'" size="mini" type="info" class="del-tag">待删除</el-tag>
          </div>
        </div>
      </template>
      <template v-slot:qty='{ row }'>
        <span v-if="row.__status === 'delete'">{{ row.qty }}</span>
        <vxe-input v-else v-model="row.qty"  placeholder="数量" align="center" size="mini" type="integer" @change="qtyChange($event, row)" >
        </vxe-input>
      </template>
      <template v-slot:price='{ row }'>
        <span v-if="row.isGift == 1">0</span>
        <vxe-input v-else-if="row.__status !== 'delete'" v-model="row.price" placeholder="单价" align="center" size="mini" type="number" @change="priceChange($event, row)" >
        </vxe-input>
        <span v-else>{{ row.price }}</span>
      </template>
    </by-table>
    <div class="product-row">
      <div class="p-left">数量：{{ num }}</div>
      <div class="p-right">
        <div class="amount-title">商品成交总金额：</div>
        <div class="amount-price">¥{{ productTotal }}</div>
      </div>
    </div>
    <div class="product-row">
      <div class="p-left"></div>
      <div class="p-right">
        <div class="amount-title">抵扣金额：</div>
        <div class="amount-price">¥{{freeAmount?freeAmount:'0.00'}}</div>
      </div>
    </div>
    <div class="product-row">
      <div class="p-left"></div>
      <div class="p-right">
        <div class="amount-title">运费：</div>
        <div class="amount-price">¥{{freight?freight:'0.00'}}</div>
      </div>
    </div>
    <div class="product-row">
      <div class="p-left"></div>
      <div class="p-right">
        <div class="amount-title">应付总金额：</div>
        <div class="amount-price" style="color:#F00; font-size: 14px;">¥{{payAmount?payAmount:'0.00'}}</div>
      </div>
    </div>
    <div class="product-row" v-if="orderValue.paidAmount">
      <div class="p-left"></div>
      <div class="p-right">
        <div class="amount-title">实付总金额：</div>
        <div class="amount-price" style="color:#F00; font-size: 14px;">¥{{orderValue.paidAmount?orderValue.paidAmount:'0.00'}}</div>
      </div>
    </div>
    <product-sku-modal ref="product" :mulit="true" @confirm="confirmProduct" />
    <product-sku-modal ref="productGift" :mulit="true" @confirm="confirmProductGift" />
    <template #footer>
      <div class="btn">
        <el-button plain size="small" @click="value = false">取消</el-button>
        <el-button type="primary" size="small" @click="btn">确定</el-button>
      </div>
    </template>
  </vxe-modal>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { add,multiply,subtract,divide } from '@/benyun/utils/accuracy'
import { batchItem } from '@/api/omsOrder'
@Component
export default class EditProductModal extends Vue {
  value=false;
  load = false;
  num:any=0;//数量
  payAmount:any=0; //应付总金额
  productTotal:any=0;//商品成交总金额
  freeAmount:any=0;//抵扣
  freight:any=0;//运费
  orderValue:any={}
  toolConfig={
    customTools:[
      {
        name: '新增商品', icon: 'el-icon-plus', event:{
          click:()=>{
            this.toolAddProduct()
          }
        }
      },
      {
        name: '添加赠品', icon: 'el-icon-plus', event:{
          click:()=>{
            this.toolAddGift();
            
          }
        }
      }
    ]
  }
  form:any={
    attr:{
      size:'mini'
    },
    columns:[
      [{
        label:'运费',
        prop:'freight',
        labelWidth:'80px',
        component:'by-input',
        compConfig:{
          attr:{
            placeholder:'保留两位小数',
            size:'mini',
            type:'number'
          }
        }
      },{
        label:'抵扣金额',
        prop:'freeAmount',
        labelWidth:'100px',
        slot:true,
        // component:'by-input',
        // compConfig:{
        //   attr:{
        //     placeholder:'保留两位小数',
        //     size:'mini'
        //   }
        // }
      },{
        label:'快速支付',
        prop:'isPay',
        slot:true
      }]
    ]
  }
  tableConfig:any={
    attr:{
      size:'mini',
      align:'center',
    },
    columns:[{
      title:'名称',
      field:'name',
      slot:true,
      width:300
    },{
      title:'数量',
      field:'qty',
      width:100,
      slot:true
    },{
      title:'单价',
      field:'price',
      width:100,
      slot:true
    },{
      title:'原价',
      field:'basePrice',
      width:100
    },{
      title:'成交金额',
      field:'amount',
      width:100
    },

    {
      title:'操作',
      action:true,
      plugins:[{
        icon:'el-icon-delete',
        name:'删除',
        event:{
          click:(item:any) => {
            this.deletaProduct(item);
          },
          show:(item:any) => {
            return item.__status !== 'delete'
          }
        }
      },{
        icon:'el-icon-refresh-left',
        name:'恢复数据',
        audit:'',
        event:{
          click:(item:any) => {
            this.restoreData(item);
          },
          show:(item:any) => {
            return item.__status === 'delete'
          }
        }
      }]
    }]
  }
  //添加商品
  toolAddProduct(){
    (this.$refs.product as any).setShow(true);
  }
  //添加赠品
  toolAddGift(){
    (this.$refs.productGift as any).setShow(true);
  }
  hide(){}
  setShow(v:boolean){
    this.value = v;
  }
  btn(){
    let data = (this.$refs.table as any).getValue();
    let formValue = (this.$refs.form as any).getValue();
    let parames:any={};
    parames.addItems=[];
    parames.addGifts=[];
    parames.delItems=[];
    parames.editItems=[];
    parames.id = this.orderValue.id;
    parames.freight=formValue.freight;
    parames.freeAmount=formValue.freeAmount;
    parames.isPay = formValue.isPay?true:false;
    for(const item of data){
      if(!item.id){
        if(item.isGift == 1){
          parames.addGifts.push({
            itemId:item.itemId,
            qty:item.qty,
            price:0
          })
        }else{
          parames.addItems.push({
            itemId:item.itemId,
            qty:item.qty,
            price:item.price
          })
        }
      }else{
        if(item.__status == 'delete'){
          parames.delItems.push(item.id)
        }else if(item.__status == 'modify'){
          parames.editItems.push({
            itemId:item.id,
            qty:item.qty,
            price:item.price
          })
        }
      }
    }
    this.load = true;
    batchItem(parames).then(()=>{
      this.value = false;
      this.load = false;
      this.$emit('handleSuccess')
    }).catch(()=>{
      this.load = false;
    })
  }
  setOrderValue(v:any){
    this.orderValue = v;
    this.$nextTick(()=>{
      let newValue:any = {};
      newValue.freight = v.freight;
      newValue.freeAmount = v.freeAmount;
      newValue.isPay = false;
      this.payAmount = v.payAmount;
      this.freeAmount = v.freeAmount;
      if(this.$refs.form){
        (this.$refs.form as any).setValue(newValue)
      }
    })
  }
  setTableValue(v:any){
    this.$nextTick(()=>{
      if(this.$refs.table){
        (this.$refs.table as any).setValue(v);
        this.totalAmount();
        this.totalNum();
      }
    })
  }
  //商品成交总金额
  totalAmount(){
    let nowData = (this.$refs.table as any).getValue();
    this.productTotal = 0;
    for(const item of nowData){
      if(Number(item.amount) && item.isGift != 1){
        this.productTotal = add(item.amount, this.productTotal)
      }
    }
    this.productTotal = this.productTotal.toFixed(2);
  }
  freeAmountChange(){
    let data = (this.$refs.form as any).getValue()
    if(data.freeAmount){
      if(Number(data.freeAmount) >= 0){
        this.freeAmount = Number(data.freeAmounte);
      }else{
        let arr:Array<any> = data.freeAmounte.split("%");
        if(arr.length == 2 && Number(arr[0]) > 0){
          const n = divide(Number(arr[0]),100)
          this.freeAmount = multiply(this.productTotal,n)
        }else{
          this.freeAmount = 0;
        }
      }
    }else{
      this.freeAmount = 0;
    }
    this.payAmountChange();
  }
  //应付总金额
  payAmountChange(){
    let t = subtract(this.productTotal, this.freeAmount);
    this.payAmount = add(t, this.freight);
    this.payAmount = this.payAmount.toFixed(2);
  }
  //商品总数量
  totalNum(){
    let nowData = (this.$refs.table as any).getValue();
    this.num = 0;
    for(const item of nowData){
      if(Number(item.qty)){
        this.num = add(Number(item.qty), Number(this.num))
      }
    }
  }
  formChange(data:any){
    if(data.code == 'freight'){
      this.freight = data.value?data.value:0;
      this.payAmountChange();
    }
  }
  //数量的变化
  qtyChange(v:any,row:any){
    if(v.value && row.price){
      row.amount = multiply(Number(v.value),Number(row.price))
    }else{
      row.amount = 0
    }
    if(row.id){
      row.__status='modify'
    }
    this.totalAmount();
    this.freeAmountChange();
    this.payAmountChange();
    this.totalNum();
  }
  //单价的变化
  priceChange(v:any,row:any){
    if(v.value && row.qty){
      row.amount =multiply(Number(v.value),Number(row.qty))
    }else{
      row.amount = 0
    }
    if(row.id){
      row.__status='modify'
    }
    this.totalAmount();
    this.freeAmountChange();
    this.payAmountChange();
  }
  //确定新增的商品
  confirmProduct(data:Array<any>){
    this.productHandle(data,false);
  }
  //新增赠品
  confirmProductGift(data:Array<any>){
    this.productHandle(data,true);
  }
  //商品处理
  productHandle(data:Array<any>,isGift:boolean){
    let nowData = (this.$refs.table as any).getValue();
    let names='';
    if(data.length > 0){
      for(const item of data){
        let t = true;
        let v = isGift ? 1 : 0;
        for(const t_item of nowData){
          if(item.id == t_item.itemId && t_item.isGift == v){
            if(!names){
              names = item.skuTitle
            }else{
              names = names + ',' + item.skuTitle
            }
            t = false;
            break;
          }
        }
        if(t){
          let obj:any={};
          obj.name = item.skuTitle; //商品名称
          obj.skuId = item.skuCode; //商品编码
          obj.itemId = item.id;
          obj.styleId = item.itemNumber; //款式编码
          obj.qty = 1;
          if(isGift){
            obj.price = 0;  //单价
            obj.isGift = 1;
          }else{
            obj.price = item.price;  //单价
            obj.isGift = 0;
          }
          
          obj.basePrice = item.price; //原价
          obj.amount = item.price;
          nowData.push(obj)
        }
      }
      (this.$refs.table as any).setValue(nowData);
     
      if(names){
        let name = isGift ? '赠品' : '商品';
        this.$alert(name+'“'+names+'”已存在，请在列表做调整！', '提示', {
          confirmButtonText: '确定',
          callback: action => {}
        });
      }
    }
  }
  //删除商品
  deletaProduct(row:any){
    let data = (this.$refs.table as any).getValue();
    let index = -1;
    for(const item of data){
      index ++;
      if(row.skuId == item.skuId && row.name == item.name && row.isGift == item.isGift){
        break;
      }
    }
    if(row.id){
      data[index].__status = 'delete'
    }else{
      data.splice(index,1);
    }
    
    (this.$refs.table as any).setValue(data);
  }
  //恢复数据
  restoreData(row:any){
    let data = (this.$refs.table as any).getValue();
    let index = -1;
    for(const item of data){
      index ++;
      if(row.skuId == item.skuId && row.name == item.name && row.isGift == item.isGift){
        break;
      }
    }
    delete data[index].__status;
    (this.$refs.table as any).setValue(data);
  }
}
</script>

<style lang="scss" scoped>
.tool-comp{
  width: 100%;
  padding-bottom: 8px;
}
.del-tag{
  margin-left: 8px;
}
.product-row{
  width: 100%;
  display: flex;
  align-items: center;
  font-size: 12px;
  padding: 4px 0;
  .p-left,.p-right{
    width: 50%;
  }
  .p-left{
    text-align: right;
  }
  .p-right{
    display: flex;
    align-items: center;
    .amount-title{
      width: 70%;
      text-align: right;
      box-sizing: border-box;
      padding-right: 8px;
    }
    .amount-price{
      width: 30%;
    }
  }
}
</style>