<template>
  <vxe-modal v-model="value" id="purchaseModel" @show="show" width="70%" height="80%" min-width="460" min-height="320" 
    show-zoom resize transfer show-footer @hide="hide" v-loading="load">
    <template #title>
      <span>生成采购单</span>
    </template>
    <el-collapse v-model="activeNames">
      <el-collapse-item title="基本信息" name="1" class="add-order-item">
        <by-form :propConfig="baseConfig" ref="baseform">
          <template v-slot:organizationName='{ value }'>
            <el-input placeholder="请选择供应商" v-model="value.organizationName" @clear="organizationClear" class="input-organizationName" size="small" clearable>
              <el-button slot="append" icon="el-icon-more" @click="handleSupplier"></el-button>
            </el-input>
          </template>
        </by-form>
      </el-collapse-item>

      <el-collapse-item title="商品信息" name="2" class="add-order-item">
        <by-table :propConfig="tableConfig" ref="table" @onChangeRow="onChangeRow"></by-table>
      </el-collapse-item>
    </el-collapse>
    <supplier-modal ref="supplierModal" @confirm="confirm" />
    <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 { toPurchaseOrder } from '@/api/omsOrder'
import { add,multiply,subtract,divide } from '@/benyun/utils/accuracy'
// import SupplierModal from "@/components/supplierModal/supplierModal.vue";
@Component({components:{}})
export default class PurchaseModel extends Vue {
  value=false;
  load = false;
  activeNames:Array<any>=['1','2']
  baseConfig:any={
    attr:{
      size:'small',
      rules:{
        organizationName:[{
          required: true, message: '供应商不能为空！', trigger: ['blur','change']
        }],
        deliveryAddress:[{
          required: true, message: '交货地点不能为空！', trigger: 'blur'
        }],
        deliveryData:[{
          required: true, message: '交货时间不能为空！', trigger: 'blur'
        }],
        delivery:[{
          required: true, message: '交货人不能为空！', trigger: 'blur'
        }],
        deliveryPhone:[{
          required: true, message: '交货人不能为空！', trigger: 'blur'
        },{
          validator: this.validatePhone, trigger: 'blur' 
        }]
      }
    },
    columns:[
      [{
        span:6,
        label:'供应商',
        prop:'organizationName',
        slot:true
      },{
        span:6,
        label:'交货地点',
        prop:'deliveryAddress',
        component:'by-input',
        compConfig:{
          attr:{
            placeholder:'请输入交货地点',
            clearable:true
          }
        }
      },{
        span:6,
        label:'交货时间',
        prop:'deliveryData',
        component:'by-date-picker',
        compConfig:{
          attr:{
            placeholder:'交货时间',
            type:'datetime',
            defaultNow:true,
            clearable:true
          }
        }
      }],
      [{
        span:6,
        label:'交货人',
        prop:'delivery',
        component:'by-input',
        compConfig:{
          attr:{
            placeholder:'请输入交货人',
            clearable:true
          }
        }
      },{
        span:6,
        label:'交货人手机',
        prop:'deliveryPhone',
        component:'by-input',
        compConfig:{
          attr:{
            placeholder:'请输入交货人手机',
            clearable:true
          }
        }
      },{
        span:6,
        label:'交货方式',
        prop:'deliveryWay',
        component:'by-input',
        compConfig:{
          attr:{
            placeholder:'请输入交货方式',
            clearable:true
          }
        }
      },{
        span:6,
        label:'物流分类',
        prop:'logisticClass',
        component:'by-input',
        compConfig:{
          attr:{
            placeholder:'请输入物流分类',
            clearable:true
          }
        }
      }]
    ]
  }

  tableConfig:any={
    attr:{
      size:'small',
      align:'center',
      seq:true
    },
    columns:[{
      title:'商品',
      field:'name',
      // width:180,
      // slot:true
    },{
      title:'数量',
      field:'qty',
      width:100,
      component:'by-input',
      compConfig:{
        attr:{
          type:'integer',
          min:0
          // isPositiveNumber:true
        }
      }
    },{
      title:'价格',
      field:'price',
      width:100,
      component:'by-input',
      compConfig:{
        attr:{
          type:'number'
        }
      }
    },{
      title:'可采购数量',
      field:'residueQty',
      width:100,
    },{
      action:true,
      width:100,
      title:'操作',
      plugins:[{
        name:'删除',
        event:{
          click:(row:any)=>{
            this.del(row)
          }
        }
      }]
    }]
  }
  validatePhone(rule:any, value:any, callback:any){
    if (value) {
      if(!/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value)) {
        callback(new Error('手机号格式不正确！'));  
      }else{
        callback();
      }
      
    } else {
      callback();
    }
  }
  del(row:any){
    let data = (this.$refs.table as any).getValue();
    let _index=-1
    for(const item of data){
      _index ++;
      if(item.itemId == row.itemId && item.name == row.name){
        break
      }
    }
    if(_index >= 0){
      data.splice(_index,1);
    }
    (this.$refs.table as any).setValue(data);
  }
  show(){
    if(this.$refs.baseform){
      (this.$refs.baseform as any).clearValue();
    }
  }
  hide(){}

  onChangeRow(row:any){
    // console.log(row,Number(row.qty),Number(row.residueQty))
    if(Number(row.qty) > Number(row.residueQty)){
      this.$message('数量不能大于可采购数量！');
      row.qty = '0';
      this.$forceUpdate()
    }
  }

  setShow(v:boolean){
    this.value = v;
  }

  setTableData(data:Array<any>){
    let newData:Array<any>=[]
    if(data.length > 0){
      for(const item of data){
        newData.push({
          orderId:item.orderId,
          itemId:item.id,
          name:item.name,
          residueQty:item.residueQty,
          qty:item.residueQty,
          price:item.price
        })
      }
    }
    this.$nextTick(()=>{
      (this.$refs.table as any).setValue(newData);
    })
  }

  handleSupplier(){
    (this.$refs.supplierModal as any).setShow(true);
  }

  confirm(data:Array<any>){
    if(data.length == 0){
      this.$message('请选择供应商！')
      return
    }
    let value:any = (this.$refs.baseform as any).getValue();
    value.organizationName = data[0].name;
    value.organizationId = data[0].id;
    (this.$refs.baseform as any).setValue(value);
  }
  organizationClear(){
    let value:any = (this.$refs.baseform as any).getValue();
    value.organizationName = '';
    value.organizationId = '';
    (this.$refs.baseform as any).setValue(value);
  }
  btn(){
    (this.$refs.baseform as any).validate().then(()=>{
      let value:any = (this.$refs.baseform as any).getValue();
      let data:Array<any>=(this.$refs.table as any).getValue();
      if(data.length > 0){
        value.items = data;
        this.load = true;
        toPurchaseOrder(value).then((res:any)=>{
          this.load = false;
          this.value = false;
          this.$message({
            message:'采购单已生成！',
            type:'success'
          })
          this.$emit('handleSuccess');
        }).catch((err:any) => {
          this.load = false;
        })
      }else{
        this.$message({
          message:'采购的商品不能为空！',
          type:'warning'
        })
      }
      
    }).catch(() => {})
    
  }
}
</script>

<style lang="scss" scoped>

</style>

<style lang="scss">
.input-organizationName{
  .el-input-group__append{
    background-color: #fff !important;
  }  
}
</style>