<template>
  <ele-modal
  custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    :title="title"
    :close-on-click-modal="false"
    width="80%"
    @close="cancel"
  >
  
  <el-form ref="form" :model="form" :rules="rules" label-width="120px">
   
      <headerTitle title="对账单信息"></headerTitle>
        <el-row>
         
          <el-col :span="12">
            <el-form-item
              label="选择订单"
              prop="orderNo"
              style="margin-bottom: 22px"
            >
            <el-input
                clearable
                v-model="form.orderNo"
                @click.native="handleOrderBtn"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item
              label="客户名称"
              prop="contactName"
              style="margin-bottom: 22px"
            >
            <el-input
                clearable
                v-model="form.contactName"
                disabled
              />
            </el-form-item>
            <el-form-item
              label="项目名称"
              prop="projectName"
              style="margin-bottom: 22px"
            >
            <el-input
                clearable
                v-model="form.projectName"
                disabled
              />
            </el-form-item>
            <el-form-item
              label="备注"
              prop="remark"
              style="margin-bottom: 22px"
            >
            <el-input
                clearable
                v-model="form.remark"
                type="textarea"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
          
              <el-form-item
              label="账期"
              prop="accountPeriod"
              style="margin-bottom: 22px"
            >
                <el-date-picker
                   v-model="form.accountPeriod"
                   value-format="yyyy-MM"
                   type="month"
                   placeholder="选择月">
                 </el-date-picker>
            </el-form-item>

           
              <el-form-item
              label="开始日期"
              prop="startDate"
              style="margin-bottom: 22px"
            >
                 <el-date-picker
                 v-model="form.startDate"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="选择日期">
               </el-date-picker>
            </el-form-item>
            <el-form-item
              label="结束日期"
              prop="endDate"
              style="margin-bottom: 22px"
            >
                 <el-date-picker
                 v-model="form.endDate"
                 type="date"
                 value-format="yyyy-MM-dd"
                 placeholder="选择日期">
               </el-date-picker>
            </el-form-item>
            <el-form-item
              label=""
              prop=""
              style="margin-bottom: 22px"
            >
            <el-button type="primary" @click="seachAccountDetail">查询明细</el-button>
            </el-form-item>
           
          </el-col>
        </el-row>
        


      

      
    
      <headerTitle title="对账明细" style="margin-top:30px;"></headerTitle>
     <inventoryTable  ref="inventoryTableref" ></inventoryTable>
        
    </el-form>
    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
    <orderListDialog ref="orderListDialogRef" @changeParent="changeOrder"></orderListDialog>
  </ele-modal>
</template>

<script>
import { emailReg, phoneReg,numberReg } from 'ele-admin';
import {acceptUnpackoptions} from '@/enum/dict';
import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import deptSelect from '@/components/CommomSelect/dept-select.vue';
import personSelect from '@/components/CommomSelect/person-select.vue';
import parentList from '@/views/saleManage/contact/components/parentList.vue'
import { getDetail} from '@/api/contractManage/contractBook';
import { getSaleOrderDetail, UpdateInformation, addInformation,deleteInformation,updateStatus} from '@/api/saleManage/saleorder';
import { addtAccountstatement,UpdatetAccountstatement,gettAccountstatementDetail,getsearchDetailListByType} from '@/api/saleManage/accountstatement';
import {getcontactlink} from '@/api/saleManage/businessFollow';
import inventoryTable from './inventoryTable.vue';
import {listOrganizations} from '@/api/system/organization';
import orderListDialog from './orderListDialog.vue';
import {copyObj} from '@/utils/util';


export default {
    mixins: [dictMixins],
    components: {
      fileUpload,
      deptSelect,
      inventoryTable,
      orderListDialog,
      parentList,
      personSelect
    },
    data() {
      let formDef = {
          id:'',
          contractId: '',
          contractName: '',
          type:1,
          orderNo:'',
          orderId:'',
          orderNum:null,
          productNum:null,
          projectName:'',
          projectId:'',
          remark:'',
          startDate:'',
          endDate:'',
          totalPrice:null
        };
   
      return {
        detailData:{},   
        payWayOptions:[],
        delDetailIds:[],
        linkNameOptions:[],
        acceptUnpackoptions,
        visible: false,
        title: '',
        row: {},
        activeName: 'base',
        formDef,
        form: copyObj(formDef),
        tableBankData: [],
        tableLinkData: [],
     // 组织机构树形结构数据
       groupTreeData: [],
       groupData:[],
        rules: {        
          orderNo: [
            { required: true, message: '请选择订单', trigger: 'change' }
          ],
          accountPeriod: [
            { required: true, message: '请选择账期', trigger: 'change' }
          ],
          startDate: [
            { required: true, message: '请选择正确的开始日期',validator: this.validateStartDate, trigger: 'change' }
          ],
          endDate: [
            { required: true, message: '请选择正确的结束日期',validator: this.validateEndDate, trigger: 'change' }
          ],
        },
     
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
      };
    },
    computed: {
     
      allcountAmount(){
        return this.$store.state.order.allcountAmount
      }
    },
   
    methods: {
 //开始日期验证
 validateStartDate(rule, value, callback) {
      if (this.form.endDate && value > this.form.endDate) {
        callback(new Error('开始日期不能大于结束日期'));
      } else {
        callback();
      }
    },
    //结束日期验证
    validateEndDate(rule, value, callback) {
      if (this.form.endDate&&this.form.startDate && value < this.form.startDate) {
        callback(new Error('结束日期不能小于开始日期'));
      } else {
        callback();
      }
    },
       //查询对账单明细
       async seachAccountDetail(){
        let {orderId,endDate,startDate}=this.form
        try {
          await this.getValidate();
          let parms={
          type:1,    //1销售订单2采购
          orderId,
          startDate,
          endDate
        }
        const data = await getsearchDetailListByType(parms);
        if(data&&data.length===0){
          return this.$message.error('没有数据')
        }
        this.$refs.inventoryTableref&&this.$refs.inventoryTableref.putTableValue(data)

        } catch (error) {
          
        }
       
        
     
       },
       //选择订单回调
       changeOrder(obj){
        this.form = Object.assign({},this.form,{
          orderId: obj.id,
          orderNo: obj.orderNo,
          contactId:obj.partaId,
          contactName:obj.partaName,
          projectName:obj.projectName,
          projectId:obj.projectId
        })
        
      },


      //对账单详情
      async gettAccountstatementDetail(id){
        this.loading = true;
        const data = await gettAccountstatementDetail(id);
        this.loading = false;
        if (data) {
          this.form = data;
            this.$refs.inventoryTableref&&this.$refs.inventoryTableref.putTableValue(data.detailList)
          this.$nextTick(()=>{
            this.$refs.form.validate();
          })          
        }
      },

   //更新联系人数据
   async getLinkInfo(contactId) {
      const data = await getcontactlink({contactId});
         if(data&&data?.length){
           this.linkNameOptions=data
         }
    },
      selectFocus(){
   if(this.linkNameOptions.length===0){
    return this.$message.error('请先选择名称')
   }
    },

 
  
    handHead(){
      
      let item={
          id:this.form.partbLinkId
        }
        this.$refs.headRef.open(item)
     },



  
    

    
      //选择订单弹框
       handleOrderBtn(){
         let item = {
           id: this.form.orderId
      }
        this.$refs.orderListDialogRef.open(item)
    },

    
      //打开新增编辑弹框
      async open(type, row,orderId) {
        this.title = type==='add'?'新增发货单':'修改';
        this.row = row;
        this.visible = true;
        if(row&&row?.id){
          this.gettAccountstatementDetail(row?.id)
        }
        
        if (type == 'add') {
          this.isUpdate = false;
        } else {
          this.isUpdate = true;
         
        }
      },

      salesmanChange(val, info){
        this.otherForm.salesmanName = info.name;
      },
      settlementModeChange(info){
        this.form.settlementModeName = info.dictValue;
      },
      ifChiefChange(value, idx){
        if(value === 1){
          this.tableLinkData.forEach(e => e.ifChief = 0);
          this.tableLinkData[idx].ifChief = 1;
        }
      },
 
    
     getValidate() {
        return Promise.all([
            new Promise((resolve, reject) => {
              this.$refs.form.validate((valid) => {
                if (!valid) {
                  reject(false);
                } else {
                  resolve(true);
                }
              });
            })
          
          ]);
     },
      async save() {
        try {
           await this.getValidate();
           // 表单验证通过，执行保存操作
           this.loading = true;
      
        if (!this.isUpdate) {
          delete this.form.id;
        } 
        let [detailList,amountData]=this.$refs.inventoryTableref.getTableValue()
        let commitData=Object.assign({},this.form,{
          detailList,
          ...amountData
        })

        if (this.isUpdate) {
          UpdatetAccountstatement(commitData)
            .then((res) => {
              this.loading = false;
              this.$message.success("修改成功");
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        } else {
          addtAccountstatement(commitData)
            .then((res) => {
              this.loading = false;
              this.$message.success("新增成功");
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
          }
        } catch (error) {
          console.log(error)
          // 表单验证未通过，不执行保存操作
        }
       
      },
      cancel() {
        this.$nextTick(() => {
          this.activeName = 'base';
          // 关闭后，销毁所有的表单数据
          this.$refs['otherForm'] &&  this.$refs['otherForm'].resetFields();
          this.$refs['formRef'] &&  this.$refs['formRef'].resetFields();
          this.$store.commit('order/clearUserData');
          this.form = copyObj(this.formDef)
          this.visible = false;
        })
      },
 
    

    }
  };
</script>
<style scoped lang="scss">
.TotalAmount{
  font-size: 16px;
  padding-right: 30px;
}

.headbox{
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .amount{
    font-size: 14px;
    font-weight: bold;
    margin-right: 20px;
  }
}
</style>