<template>
<div class="reply" ref = "replyModal">
  <a-modal
    :title="(defultMethods == 'add')?'新增':'编辑'"
    width="85%"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    :getContainer ='()=>$refs.replyModal'
    @cancel="handleCancel"
    destroyOnClose>
     <template #footer>
      <a-upload  name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"   @change="handleImportExcel" :customRequest="implementImport" >
        <a-button  type="primary">导入</a-button>
      </a-upload>
        <a-button  @click="handleCancel" style="margin-left: 8px;">取消</a-button>
        <a-button  type="primary"  @click="handleOk">保存</a-button>
      </template>
     <div class="table-page-search-wrapper">
      <!-- 主表单区域 -->
       <a-form-model layout="inline" ref="form" :model="formState" :rules="validatorRules">
          <a-row :gutter="24">
            <a-col :md="8" :sm="8">
              <a-form-model-item label="编号" prop="code">
                <a-input   placeholder="请输入"  v-model="formState.code" />
              </a-form-model-item>
            </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="名称"  prop="name">
                <a-input placeholder="请输入名称" v-model="formState.name"/>
              </a-form-model-item>
           </a-col>
            <a-col :md="8" :sm="8">
              <a-form-model-item label="合计"  prop="totalNum">
                 <a-input placeholder="请输入" v-model="formState.totalNum" readOnly/>
               </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
              <a-col :md="24" :sm="8"> 
               <a-form-model-item label="备注信息"  class="nresume" style="height:100px !important">
                 <a-input type="textarea" placeholder="请输入" v-model="formState.demo"/>
               </a-form-model-item>
              </a-col>
            </a-row>
      </a-form-model>

      <!-- 子表单区域 -->
      <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="棉纱" :key="refKeys[0]" :forceRender="true">
          <a-button type="primary"  @click="addList" style="margin-bottom: 1%;">增行</a-button>
          <a-table
           bordered
           :columns="syCottonYarnBTable.columns"
           :data-source="syCottonYarnBTable.dataSource"
           :loading="syCottonYarnBTable.loading"
           :scroll="{x: 1800,y:300 }"
           :pagination="false"
          >
          <!-- 表头--日期 -->
          <span slot="orderDateTitle" class="form-table-heard">
             日期
          </span>
          <!-- 表头--入库单号 -->
          <span slot="receiptNoTitle" class="form-table-heard">
             入库单号
          </span>
          <!-- 表头--每吨纱价格 -->
          <span slot="priceTitle" class="form-table-heard">
            每吨纱价格
          </span>
          <!-- 表头--集装箱号 -->
          <span slot="containerNoTitle" class="form-table-heard">
             集装箱号
          </span>
           <span slot="reasonTitle" class="form-table-heard">
             原因
          </span>
          <!-- 表头--总价 -->
          <span slot="totalPriceTitle" class="form-table-heard">
             总价
          </span>
          <!-- 日期 -->
           <span slot="orderDate" slot-scope="text, record,index">
                <a-date-picker
                    placeholder="请选择"
                    v-model="record.orderDate"
                  />
          </span>
            <!-- 入库单号 -->
          <span slot="receiptNo" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.receiptNo" />
          </span>
            <!-- 吨数 -->
          <span slot="tonnage" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.tonnage" />
          </span>
           <!-- 柜子数量 -->
          <span slot="cabinets" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.cabinets" />
          </span>
          <!-- 每吨纱价格 -->
          <span slot="price" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.price" />
          </span>
          <!-- 集装箱号 -->
          <span slot="containerNo" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.containerNo" />
          </span>
           <!-- 原因 -->
          <span slot="reason" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.reason" />
          </span>
          <!-- 总价 -->
          <span slot="totalPrice" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.totalPrice" @change="changeTotalPrice"/>
          </span>
          <!-- 备注 -->
          <span slot="demo" slot-scope="text, record, index">
                  <a-input placeholder="请输入" v-model="record.demo" />
          </span>
          </a-table>
          <!-- <j-editable-table
            :ref="refKeys[0]"
            :loading="syCottonYarnBTable.loading"
            :columns="syCottonYarnBTable.columns"
            :dataSource="syCottonYarnBTable.dataSource"
            :maxHeight="300"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"/> -->
        </a-tab-pane>
      </a-tabs>

     </div>
  </a-modal>
</div>
</template>

<script>

  import moment from 'moment'
  import pick from 'lodash.pick'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { putAction,postAction,getAction } from '@/api/manage'
  import {fileDetail} from '@api/oa/cd-sy-cotton'


  export default {
    name: 'SyCottonYarnModal',
    mixins: [JEditableTableMixin],
    data() {
      return {
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
              name:[{required: true, message: '名称不能为空!'}],
              code:[{required: true, message: '编号不能为空!'}],
        },
        refKeys: ['syCottonYarnB', ],
        activeKey: 'syCottonYarnB',
        formState:{},
        defultMethods:'add',
        zhuId:'',
        passVerification:'yes',
        // 搬运装卸费用-棉纱-子表
        syCottonYarnBTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
            // title: '日期',
            align: "center",
            dataIndex: 'orderDate',
            width: '9%',
            scopedSlots: { customRender: 'orderDate' },
            slots:{title:'orderDateTitle'}
          },
          {
            // title: '入库单号',
            align: "center",
            dataIndex: 'receiptNo',
            width: '9%',
            scopedSlots: { customRender: 'receiptNo' },
            slots:{title:'receiptNoTitle'}
          },
          {
            title: '吨数',
            align: "center",
            dataIndex: 'tonnage',
            width: '9%',
            scopedSlots: { customRender: 'tonnage' },
          },
          {
            title: '柜子数量',
            align: "center",
            dataIndex: 'cabinets',
            width: '9%',
            scopedSlots: { customRender: 'cabinets' },
          },
          {
            // title: '每吨纱价格',
            align: "center",
            dataIndex: 'price',
            width: '9%',
            scopedSlots: { customRender: 'price' },
            slots:{title:'priceTitle'}
          },
           {
            // title: '集装箱号',
            align: "center",
            dataIndex: 'containerNo',
            width: '9%',
            scopedSlots: { customRender: 'containerNo' },
            slots:{title:'containerNoTitle'}
          },
          {
            // title: '原因',
            align: "center",
            dataIndex: 'reason',
            width: '9%',
            scopedSlots: { customRender: 'reason' },
            slots:{title:'reasonTitle'}
          },
          {
            // title: '总价',
            align: "center",
            dataIndex: 'totalPrice',
            width: '9%',
            scopedSlots: { customRender: 'totalPrice' },
            slots:{title:'totalPriceTitle'}
          },
          {
            title: '签字',
            align: "center",
            dataIndex: 'jhyName',
            width: '9%',
            scopedSlots: { customRender: 'jhyName' },
          },
          {
            title: '备注',
            align: "center",
            dataIndex: 'demo',
            width: '9%',
            scopedSlots: { customRender: 'demo' },
          },
          ]
        },
        url: {
          add: "/oa/syCottonYarn/add",
          edit: "/oa/syCottonYarn/edit",
          syCottonYarnB: {
            list: '/oa/syCottonYarn/querySyCottonYarnBByMainId'
          },
        }
      }
    },
    methods: {
      // 获取表头信息
      getHeaderList(id){
        getAction('/oa/syCottonYarn/queryById', {id:id}).then((res) => {
          if(res.success){
            var zhuId = '' //主表id
             this.formState=res.result //详情
             zhuId = res.result.id
             this.getTable(zhuId)
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      getTable(id){
        getAction('/oa/syCottonYarn/querySyCottonYarnBByMainId', {id:id}).then((res) => {
          if(res.success){
              res.result.map(item =>{
              if(item.orderDate !==''&& item.orderDate){
                item.orderDate = moment(item.orderDate)
              }
            })
            this.syCottonYarnBTable.dataSource = res.result
          }else{
            this.$message.warning(res.message)
          }
        })
      },
      addList(){
        this.syCottonYarnBTable.dataSource.push({})
      },
      //总价改变
      changeTotalPrice(){
        var Hj = 0
       this.syCottonYarnBTable.dataSource.map(item=>{
         Hj+= Number(item.totalPrice)
       })
       this.formState.totalNum = Hj
       this.$forceUpdate()
      },
 
      /** 调用完edit()方法之后会自动调用此方法 */
      // editAfter() {
      //   this.$nextTick(() => {
      //     this.form.setFieldsValue(pick(this.model, 'name', 'code', 'demo', ))
          // 时间格式化
          // this.form.setFieldsValue({ ckTime: this.model.ckTime ? moment(this.model.ckTime) : null })
          // this.form.setFieldsValue({ rsxzTime: this.model.rsxzTime ? moment(this.model.rsxzTime) : null })
          // this.form.setFieldsValue({ cwjlTime: this.model.cwjlTime ? moment(this.model.cwjlTime) : null })
        // })
        // 加载子表数据
      //   if (this.model.id) {
      //     let params = { id: this.model.id }
      //     this.requestSubTableData(this.url.syCottonYarnB.list, params, this.syCottonYarnBTable)
      //   }
      // },
 
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        //时间格式化
        // main.ckTime = main.ckTime ? main.ckTime.format('YYYY-MM-DD HH:mm:ss') : null;
        // main.rsxzTime = main.rsxzTime ? main.rsxzTime.format('YYYY-MM-DD HH:mm:ss') : null;
        // main.cwjlTime = main.cwjlTime ? main.cwjlTime.format('YYYY-MM-DD HH:mm:ss') : null;
        return {
          ...main, // 展开
          syCottonYarnBList: allValues.tablesValue[0].values,
        }
      },
       //保存
      handleOk(){
        this.$refs.form.validate(async valid => {
         if(valid){
           var obj = this.formState
           this.syCottonYarnBTable.dataSource.map(item=>{
             if(item.orderDate!==''&&item.orderDate){
               item.orderDate = moment(item.orderDate).format('YYYY-MM-DD HH:mm:ss');
             }
           })
           obj.syCottonYarnBList = this.syCottonYarnBTable.dataSource
           await this.judageTablez(obj.syCottonYarnBList)
           if(this.defultMethods == 'add' && this.passVerification == 'yes'){
              postAction(this.url.add, obj).then(res => {
                    if (res.success) {
                      this.$message.success('新增成功')
                      this.handleCancel()
                      this.$emit('close')
                    }else{
                       this.$message.error(res.message);
                    }
                })
           }else if(this.passVerification == 'yes'){
             putAction(this.url.edit, obj).then((res) => {
             if(res.success){
             this.$message.success('编辑成功')
             this.handleCancel()
             this.$emit('close')
            }else{
            this.$message.warning(res.message)
            }  
            })
           }
         }
         })
      },
      judageTablez(data){
        this.passVerification = 'yes'
        if(data.length == 0){
          this.$message.error('请添加子表数据!');
          this.passVerification = 'no'
        }else{
          for (var i=0; i<data.length;i++){
             var tableRow = data[i];
             var required = [
              {key:'orderDate',value:'日期'},
              {key:'receiptNo',value:'入库单号'},
              {key:'price',value:'每吨纱价格'},
              {key:'containerNo',value:'集装箱号'},
              {key:'reason',value:'原因'},
              {key:'totalPrice',value:'总价'},
              ]
             for(var j=0 ; j<required.length;j++){
                if(tableRow[required[j].key] == null || tableRow[required[j].key] == "" || tableRow[required[j].key] == undefined){
                  this.$message.error('第'+(i+1)+'行'+required[j].value+'无值，无法保存');
                  this.passVerification = 'no'
                  return
                }
             }
          }
        }
      },
        // 导入
    implementImport(file) {
      const formData = new FormData()
      formData.append('file', file.file)
      fileDetail(formData).then(res => {
        // this.loading = false
        if (res.success) {
          // this.visible = true
          this.message = res.message.split('；').filter((element) => {
             return element !== ""; 
          });
          this.file = file
          this.$message.success('导入成功')
        }else{
          this.$message.error(res.message);
        }
      })
      },
        //关闭
      handleCancel(){
        this.syCottonYarnBTable.dataSource=[]
        this.formState = {}
        this.visible = false
        this.defultMethods='add'
        this.zhuId = ''
        this.$emit('close')
      },
    }
  }
</script>

<style scoped lang="less">
/deep/ .nresume .ant-input{
  height: 100px !important;
}
/deep/ .td{
  text-align:center;
}
.form-table-heard:before {
      content: '*';
      color: red;
}
</style>