<template>
    <a-modal
      :title="title"
       width="95%"
      :visible="visible"
      :maskClosable="false"
      switchFullscreen
      @cancel="handleCancel"
      @ok='handleOk'
      >
      <template slot="footer">
        <a-button  @click="handleCancel">关闭</a-button>
        <a-button type="primary"  @click="handleOk" v-if="title!=='订单操作'">保存</a-button>
     </template>
      <a-card :bordered="false" class="top" style="margin-bottom:1%;margin-top:1%" :loading = 'loading'>
        <div class="table-page-search-wrapper">
            <a-form-model layout="inline" @keyup.enter.native="searchQuery" :model="form" :rules="rules"  ref="form">
                <a-row :gutter="24">
                    <a-col  :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="生产组织" prop='orgName' >
                            <a-input-search placeholder="请选择" v-model="form.orgName"  @search="onSearchProductionOrg" readOnly></a-input-search>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="单据号">
                            <a-input placeholder="自动生成" v-model="form.orderCode" disabled></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="单据日期" prop='orderDate'>
                            <a-date-picker showTime valueFormat="YYYY-MM-DD" format = "YYYY-MM-DD" v-model="form.orderDate" style="width:100%" />
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="单据状态">
                            <a-input placeholder="请输入" v-model="form.state"  disabled></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="业务员">
                            <a-input-search placeholder="请选择" v-model="form.salesperson" @search="onSearchPerson" readOnly ></a-input-search>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="计划部门">
                            <a-input-search placeholder="请选择" v-model="form.planDept" @search="onSearchPlanDept" readOnly></a-input-search>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="项目名称" prop='projectName'>
                            <a-input-search placeholder="请选择" v-model="form.projectName" @search="onSearchProject" readOnly></a-input-search>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="项目编码" prop='projectCode'>
                            <a-input placeholder="请选择" v-model="form.projectCode" disabled></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="业务类型" prop='type'>
                            <a-select v-model="form.type"  style='width:100%'  >
                                <a-select-option value='工装'> 工装</a-select-option>
                                <a-select-option value='家装'> 家装</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="制单人">
                            <a-input placeholder="自动" v-model="form.createBy"  disabled></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="审核人">
                            <a-input placeholder="自动" v-model="form.reviewer" disabled></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="4">
                        <a-form-model-item label="工单号" prop='workNo'>
                            <a-input placeholder="请输入" v-model="form.workNo" ></a-input>
                        </a-form-model-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                        <a-form-model-item label="备注"  :labelCol="{offset: 1}" >
                            <a-input placeholder="请输入" v-model="form.remarks"></a-input>
                        </a-form-model-item>
                    </a-col>                    
                </a-row>
            </a-form-model>
        </div>
     </a-card>
     <a-card :bordered="false" class="three" style="margin-bottom:1%" >
       <div class="table-operator">
            <a-button type="danger" size="small" :disabled="form.state!='开立'" @click="addList" >增行</a-button>
            <a-button size="small" @click="delectRow" :disabled="form.state!='开立'" >删行</a-button>
            <a-button size="small" @click="productWarehous" :disabled="activeKey!=='finishProduct'||defaultMethod=='add'||form.state=='开立'">成品入库</a-button>
            <a-button size="small" @click="materiaWarehous" :disabled="activeKey!=='material'||defaultMethod=='add'||form.state=='开立'">材料出库</a-button>
            <a-button size="small" @click="KSWarehousing" :disabled="activeKey!=='finishProduct'||defaultMethod=='add'||form.state=='开立'">框/扇入库</a-button>
            <a-button size="small" @click="KSOutbound" :disabled="activeKey!=='finishProduct'||defaultMethod=='add'||form.state=='开立'">框/扇出库</a-button>
            <a-button size="small" @click="sendOrReceive('in')" :disabled="activeKey!=='SurplusMaterials'||defaultMethod=='add'||form.state=='开立'">余料入库</a-button>
            <a-button size="small" @click="editNum()" :disabled="defaultMethod=='add'||form.state=='开立'">修改已执行数量</a-button>
            <!-- <a-button size="small" @click="sendOrReceive('out')" :disabled="activeKey!=='SurplusMaterials'||defaultMethod=='add'||form.state=='开立'">杂发</a-button> -->
       </div>
       <a-tabs v-model="activeKey" @change="handleChangeTabs">
            <a-tab-pane tab="成品明细" :key="refKeys[0]" :forceRender="true">
               <productDetails ref="productDetails" :title="title"></productDetails>
            </a-tab-pane>
            <a-tab-pane tab="材料明细" :key="refKeys[1]" :forceRender="true">
               <material ref="material"  @clearn="clearnExecute" :title="title"></material>
            </a-tab-pane>
            <a-tab-pane tab="入库暂存" :key="refKeys[2]" :forceRender="true">
                <TemporaryStorage ref='TemporaryStorage'></TemporaryStorage>
            </a-tab-pane>
            <a-tab-pane tab="余料管理" :key="refKeys[3]" :forceRender="true">
                <SurplusMaterials ref='SurplusMaterials' @ok="close" :title="title"></SurplusMaterials>
            </a-tab-pane>
        </a-tabs>
       
    </a-card>
    <productWarehousModel ref="productWarehousModel" @ok="RefreshList('product')"></productWarehousModel>
    <KSOutbound ref="KSOutbound" @ok="RefreshList('out')"></KSOutbound>
    <KSWarehousing ref="KSWarehousing" @ok="RefreshList('ware')"></KSWarehousing>
    <materiaWaring ref="materiaWaring" @ok="RefreshMateriaList()"></materiaWaring>
    <organizationPopup ref="organizationPopup" @okData="okDataOrganization"></organizationPopup>
    <OperatorsPopup ref="OperatorsPopup" @okData="okDataOperators"></OperatorsPopup>
    <deparmentPopup ref="deparmentPopup" @okData="okDataDeparment"></deparmentPopup>
    <projectPopup ref="projectPopup" @okData="okData"></projectPopup>
    </a-modal>
  </template>
  <script>
      import alertModal from '../../../../plugins/modal'
      import { FormTypes } from '@/utils/JEditableTableUtil'
      import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
      import productDetails from './productDetails'
      import material from './material'
      import TemporaryStorage from './TemporaryStorage'
      import SurplusMaterials from './SurplusMaterials'
      import productWarehousModel from './productWarehousModel'
      import KSOutbound from './KSOutbound'
      import KSWarehousing from './KSWarehousing'
      import materiaWaring from './materiaWaring'
      import moment from "moment"
      import { httpAction ,getAction,postAction,putAction} from '@/api/manage'
      import organizationPopup from '../../Popup/organizationPopup.vue'
      import OperatorsPopup from '../../Popup/OperatorsPopup.vue'
      import deparmentPopup from '../../Popup/deparmentPopup.vue'
      import projectPopup from '../../Popup/projectPopup'
      export default {
        name: 'materialProcurementAdd',
        mixins: [JEditableTableModelMixin],
        components: {
            productDetails,
            material,
            TemporaryStorage,
            SurplusMaterials,
            organizationPopup,
            OperatorsPopup,
            deparmentPopup,
            projectPopup,
            productWarehousModel,
            KSOutbound,
            KSWarehousing,
            materiaWaring
        },
        data() {
          return {
            visible:false,
            form:{},
            execute:undefined,
            defaultMethod:'add',
            rules:{
              orgName: [
                { required: true, trigger: 'change' },
              ],
              orderDate:[
                { required: true, trigger: 'change' },
              ],
              projectName:[
                { required: true, trigger: 'change' },
              ],
              projectCode:[
                { required: true, trigger: 'change' },
              ],
              type:[
                { required: true, trigger: 'change' },
              ],
              workNo:[
                { required: true, trigger: 'change' },
              ],
            },
            dataSource:[],
            originalProductDeatil:[],//保存为增行钱的成品明细列表
            originalMaterial:[],//保存为增行钱的材料明细列表
            loading:false,
            // ipagination:{},
            selectedRowKeys:[],
            title:'新增',
            selectedRows:[],
            activeKey:'finishProduct',
            refKeys:['finishProduct','material','TemporaryStorage','SurplusMaterials'],
          }
        },
        created() {
          
        },
        methods: {
            handleCancel(){
                this.visible=false
                this.loading=false
                this.defaultMethod='add'
                this.activeKey='finishProduct',
                this.execute = ''
                this.dataSource = [] 
                this.form={ }
                this.selectedRowKeys = []
                this.selectedRows = []
                
                this.originalProductDeatil = []
                this.$refs.productDetails.form.dataSource =[]
                this.$refs.productDetails.planOrg=''
                this.originalMaterial  = []
                this.$refs.material.form.dataSource = []
                this.$refs.material.planOrg=''
                this.$refs.TemporaryStorage.planOrg=[]
                this.$refs.TemporaryStorage.dataSource = []
                this.$refs.SurplusMaterials.form.dataSource = []
                this.$refs.SurplusMaterials.planOrg= ''
                
                this.$emit('ok')
            },
            handleOk(){
                this.$refs.form.validate(success => {
                    if (success) {
                        var arrValid = [true]
                        if(this.$refs.productDetails.form.dataSource.length!==0){
                            arrValid.push(this.$refs.productDetails.validateList())
                        }
                        if(this.$refs.material.form.dataSource.length!==0){
                            arrValid.push(this.$refs.material.validateList())
                        }
                        if(this.$refs.SurplusMaterials.form.dataSource.length!==0){
                            arrValid.push(this.$refs.SurplusMaterials.validateList())
                        }
                        if(arrValid.indexOf(false) == -1){
                            var madeProductionOrdersPage = this.form
                            madeProductionOrdersPage.madeProductionOrdersFinishedList = this.$refs.productDetails.form.dataSource
                            madeProductionOrdersPage.madeProductionOrdersMaterialList = this.$refs.material.form.dataSource
                            madeProductionOrdersPage.madeProductionOrdersInList = this.$refs.TemporaryStorage.dataSource
                            madeProductionOrdersPage.madeProductionOrdersOutList = this.$refs.SurplusMaterials.form.dataSource
                            this.loading = true
                            if(this.defaultMethod=='add'){
                                alertModal.loading("执行中，请稍后！")
                                postAction('/productionOrder/madeProductionOrders/add', madeProductionOrdersPage).then((res) => {
                                    alertModal.closeLoading();
                                    if (res.success) {
                                        this.$message.success('添加成功！');
                                        this.$emit('ok')
                                        this.handleCancel()
                                    } else {
                                        this.$message.error(res.message);
                                    }
                                }).finally(() => {
                                    this.loading = false
                                })
                            }else{
                                alertModal.loading("执行中，请稍后！")
                                postAction('/productionOrder/madeProductionOrders/edit', madeProductionOrdersPage).then((res) => {
                                    alertModal.closeLoading();
                                    if (res.success) {
                                        this.$emit('ok')
                                        this.handleCancel()
                                        this.$message.success('编辑成功！');
                                    } else {
                                        this.$message.error(res.message);
                                    }
                                }).finally(() => {
                                    this.loading = false
                                })
                            }   
                        }else{
                            this.$message.warning('请检查子表必填项')
                        }             
                    }
                })
            },
            //获取主表信息
            getMainData(id){
                getAction('/productionOrder/madeProductionOrders/queryById',{id:id}).then(res=>{
                    if(res.success){
                       this.form=res.result
                       this.getProductData(this.form.id)
                       this.getMaterialData(this.form.id)
                       this.getTemporaryStorageData(this.form.id)
                       this.getSurplusMaterialsData(this.form.id)
                    }else{
                      this.$message.error(res.message);
                    }
                })
            },
            //获取子表信息
            getProductData(id){
                //成品明细
                this.originalProductDeatil = []//保存为增行钱的成品明细列表
                getAction('/productionOrder/madeProductionOrders/queryMadeProductionOrdersFinishedByMainId',{id:id}).then(res=>{
                    if(res.success){
                        this.originalProductDeatil = Array.from(res.result)
                        this.$refs.productDetails.form.dataSource =res.result
                        this.$refs.productDetails.planOrg=this.form.pkOrg
                        this.$refs.productDetails.form.dataSource.map((item,index)=>{
                            item.rowNo =index+1
                       })
                       
                    }else{
                      this.$message.error(res.message);
                    }
                })
            },
            //获取子表信息
            getMaterialData(id){
                //材料明细
                this.originalMaterial = []//保存为增行钱的材料明细列表
                getAction('/productionOrder/madeProductionOrders/queryMadeProductionOrdersMaterialByMainId',{id:id}).then(res=>{
                    if(res.success){
                        this.originalMaterial  = Array.from(res.result)
                        this.$refs.material.form.dataSource =res.result
                        this.$refs.material.planOrg=this.form.pkOrg
                        this.$refs.material.form.dataSource.map((item,index)=>{
                            item.rowNo =index+1
                       })
                       
                    }else{
                      this.$message.error(res.message);
                    }
                })
            },
            
             //获取子表信息
             getTemporaryStorageData(id){
                //入库暂存
                getAction('/productionOrder/madeProductionOrders/queryMadeProductionOrdersInByMainId',{id:id}).then(res=>{
                    if(res.success){
                        this.$refs.TemporaryStorage.planOrg=this.form.pkOrg
                        this.$refs.TemporaryStorage.dataSource =res.result
                        this.$refs.TemporaryStorage.dataSource.map((item,index)=>{
                            item.rowNo =index+1
                       })
                    }else{
                      this.$message.error(res.message);
                    }
                })
            },
             //获取子表信息
             getSurplusMaterialsData(id){
                //余料管理
                getAction('/productionOrder/madeProductionOrders/queryMadeProductionOrdersOutByMainId',{id:id}).then(res=>{
                    if(res.success){
                        this.$refs.SurplusMaterials.form.dataSource =res.result
                        this.$refs.SurplusMaterials.planOrg=this.form.pkOrg
                        this.$refs.SurplusMaterials.form.dataSource.map((item,index)=>{
                            item.rowNo =index+1
                       })
                       
                    }else{
                      this.$message.error(res.message);
                    }
                })
            },
            //查询生产组织
            onSearchProductionOrg(){ 
                    this.$refs.organizationPopup.visible = true
                    this.$refs.organizationPopup.getData()
            },
            //查询业务员
            onSearchPerson(){
                if(this.form.orgName&&this.form.orgName!==''){
                    this.$refs.OperatorsPopup.visible = true
                    this.$refs.OperatorsPopup.getData(this.form.pkOrg)
                }else{
                    this.$message.warning('请选择生产组织！')
                }
            },
            //查询部门
            onSearchPlanDept(){
                if(this.form.orgName&&this.form.orgName!==''){
                    this.$refs.deparmentPopup.visible = true
                    this.$refs.deparmentPopup.getData(this.form.pkOrg)
                }else{
                    this.$message.warning('请选择生产组织！')
                }
            },
            //选择项目
            okData(data){
                this.$set(this.form,'projectCode',data.Code)
                this.$set(this.form,'projectName',data.Name)
                this.$set(this.form,'project',data.ID)
                this.$refs.productDetails.form.dataSource.map((item,index)=>{
                    item.projectCode = data.Code
                    item.projectName = data.Name
                })
                this.$refs.material.form.dataSource.map((item,index)=>{
                    item.projectCode = data.Code
                    item.projectName = data.Name
                })
                this.$refs.SurplusMaterials.form.dataSource.map((item,index)=>{
                    item.projectCode = data.Code
                    item.projectName = data.Name
                })
                if(this.form.projectName&&this.form.projectName!==''){
                    this.$refs.form.clearValidate(['projectName']);
                }
                if(this.form.projectCode&&this.form.projectCode!==''){
                    this.$refs.form.clearValidate(['projectCode']);
                }
            },
            //查询生产组织
            onSearchProject(){
                    if(this.form.orgName&&this.form.orgName!==''){
                        this.$refs.projectPopup.visible = true
                        this.$refs.projectPopup.getData(this.form.pkOrg)
                    }else{
                        this.$message.warning('请选择生产组织！')
                    }
            },
            addList(){
                if(this.activeKey=='finishProduct'){
                    this.$refs.productDetails.addList(this.form.projectCode,this.form.projectName)
                }else if(this.activeKey=='material'){
                    this.$refs.material.addList(this.form.projectCode,this.form.projectName)
                }else if(this.activeKey=='SurplusMaterials'){
                    this.$refs.SurplusMaterials.addList(this.form.projectCode,this.form.projectName)
                }
            },
            delectRow(){
                if(this.activeKey=='finishProduct'){
                    this.$refs.productDetails.delectRow()
                }else if(this.activeKey=='material'){
                    this.$refs.material.delectRow()
                }else if(this.activeKey=='SurplusMaterials'){
                    this.$refs.SurplusMaterials.delectRow()
                }
            },
            clearnExecute(){
                this.execute = ''
            },
            //选择组织
            okDataOrganization(data){
                this.$set(this.form,'orgName',data.Name)
                this.$set(this.form,'orgCode',data.Code)
                this.$set(this.form,'pkOrg',data.ID)
                this.$refs.productDetails.planOrg=this.form.pkOrg
                this.$refs.material.planOrg=this.form.pkOrg
                this.$refs.SurplusMaterials.planOrg=this.form.pkOrg
                if(this.form.orgName&&this.form.orgName!==''){
                    this.$refs.form.clearValidate(['orgName']);
                }
            },
            //选择业务员
            okDataOperators(data){
                this.$set(this.form,'salesperson',data.Name)
                this.$set(this.form,'salespersonId',data.ID)
            },
            //选择部门
            okDataDeparment(data){
                this.$set(this.form,'planDept',data.Name)
                this.$set(this.form,'planDeptId',data.ID)
            },
            //成品入库
            productWarehous(){
                this.$refs.productWarehousModel.visible = true
                this.$refs.productWarehousModel.form.dataSource = this.originalProductDeatil
            },
             //打开框/扇入库弹窗
            KSWarehousing(){
                this.$refs.KSWarehousing.visible = true
                this.$refs.KSWarehousing.form.dataSource = this.originalProductDeatil
            },
            //打开框/扇出库弹窗
            KSOutbound(){
                this.$refs.KSOutbound.visible = true
                this.$refs.KSOutbound.form.dataSource = this.originalProductDeatil
            },
            //打开材料出库弹窗
            materiaWarehous(){
              
                  //材料明细
                  this.originalMaterial = []//保存为增行钱的材料明细列表
                  getAction('/productionOrder/madeProductionOrders/queryMadeProductionOrdersMaterialByMainIdAndWh',{id:this.form.id}).then(res=>{
                      if(res.success){
                          this.originalMaterial  = Array.from(res.result)
                          this.$refs.material.form.dataSource =res.result
                          this.$refs.material.planOrg=this.form.pkOrg
                          this.$refs.material.form.dataSource.map((item,index)=>{
                              item.rowNo =index+1
                         })
                         
                         this.$refs.materiaWaring.visible = true
                         this.$refs.materiaWaring.form.dataSource = this.originalMaterial
                      }else{
                        this.$message.error(res.message);
                      }
                  })
              
            },
            //成品入库，框/扇入库，框/扇出库执行完接口重新获取成品明细，和入库暂存列表
            RefreshList(data){
                this.getProductData(this.form.id)
                if(data!=='product'){
                    this.getTemporaryStorageData(this.form.id)
                }
            },
            //触发杂发杂收接口
            sendOrReceive(data){
                 this.$refs.SurplusMaterials.sendOrReceive(data)
            },
            //修改已执行数量
            editNum(){
                if(this.activeKey=='finishProduct'){
                    if(this.$refs.productDetails.selectedRowKeys.length!==1){
                        this.$message.warning('请勾选一条数据！')
                    }else{
                        this.$message.info('请修改已执行数量，鼠标移出后保存！')
                        this.$refs.productDetails.editNum(this.$refs.productDetails.selectedRowKeys[0])
                    }
                }else if(this.activeKey=='material'){
                    if(this.$refs.material.selectedRowKeys.length!==1){
                        this.$message.warning('请勾选一条数据！')
                    }else{
                        this.$message.info('请修改已执行数量，鼠标移出后保存！')
                        this.$refs.material.editNum(this.$refs.material.selectedRowKeys[0])
                    }
                }
            },
            //材料出库后重新获取材料明细列表
            RefreshMateriaList(){
                this.getMaterialData(this.form.id)
            },
            //杂发杂收接口执行结果
            close(data){
                if(data=='1'){
                    this.handleCancel()
                }
            }
        }
      }
  </script>
  
  <style scoped lang="less">
    /* @import '~@assets/less/common.less' */
    /deep/.ant-input{
        height:29px;
    }
    /deep/.ant-select-selection--single {
        height: 29px;
    }
    /deep/.ant-select{
        font-size: 12px;
    }
    /deep/.ant-form label{
        font-size: 12px;
    }
    /deep/.table-page-search-wrapper .ant-form-inline .ant-form-item{
        margin-bottom:9px
    }
    /deep/.moddle>.ant-card-body{
        padding-bottom:0px;
        padding-top: 12px;
    }
    /deep/.top>.ant-card-body{
        padding-bottom:0px;
        padding-top: 12px;
    }
    /deep/.ant-btn{
        height:28px
    }
    /deep/.ant-modal-body{
        padding-bottom: 0px;
        padding-top: 0px;
    }
    // /deep/.ant-modal-body{
    //     background: #f0f2f5;
    // }
    /deep/.ant-modal-content{
        background: #f0f2f5;
    }
    /deep/.ant-card-body .table-operator {
        margin-bottom: 0px;
    }
    /deep/.three>.ant-card-body{
        padding-bottom:12px;
        padding-top: 12px;
    }
    /deep/.bottom>.ant-card-body{
        padding-bottom:0px;
        padding-top: 12px;
    }

    /deep/.ant-calendar-picker{
        min-width: 0px !important;  
    }
    /deep/.sonItem {
        margin-bottom:0px !important
    }
    /deep/#sonList>.ant-spin-nested-loading>.ant-spin-container>.ant-table>.ant-table-content>.ant-table-scroll>.ant-table-body>.ant-table-fixed>.ant-table-tbody > tr > td {
        padding: 0px 8px !important;
    }
    /deep/.highlight-row {
        background-color: #E6F7FF;
    }
     // 表单校验隐藏提示文字
     /deep/.ant-form-explain{
      display:none
    }
  </style>