<template>
  <div v-show="show">
    <bill-editor ref="detail" :list="detailtList" :defData="detailData"></bill-editor>

    <info-model
      ref="detailModel"
      v-model="visible"
      :config="modelConfig"
      @change="setinfo"
      :ibValidates="[
        'vaildateItemInbound',
        'vaildateItemCategory',
        'vaildateItemLicense',
        'vaildateItemVol',
        'vaildateSuppilerAndCustomer',
        'vaildateLicense',
        'vaildateCargoOwnerScop',
      ]"
    />

    <view-supplier v-model="showViewSupplier" :item="viewSupplierItem" />

    <view-commodity v-model="showCommodity" :item="viewCommodity" />

    <split-bill
      v-model="splitVisible"
      :formItems="splitFormItems"
      :columns="splitColumns"
      :data="splitOriginItem"
      :splitedCallback="splitedCallback"
      :confirmLoading="confirmLoading"
      :rcvType="detailData ? detailData.main.rcvType : null"
      @ok="handleSpliteOk"
    />

    <p-modal
      title="商品维护"
      :visible="maintainVisible"
      :dialogStyle="{ top: '20px' }"
      :width="'90%'"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="box-p20-bg">
        <c-cditor
          v-if="maintainVisible"
          ref="itemsEditor"
          :detailItem="detailItem"
          :isSingle="true"
          @changeStep="handleItemsComplete"
        />
      </div>
    </p-modal>

    <a-affix :offsetBottom="0" class="footer">
      <div class="footer_bat">
        <span v-for="item of items" :key="item.name" class="footer_bat-item">
          {{ item.label }}:<span class="numClass">{{ item.value }}</span></span
        >
      </div>
    </a-affix>

    <login-modal v-model="loginVisible" title="双人收货登录" @onLogined="onLogined" />

    <imgsUpload
      v-model="isUpload"
      :isView="lookats"
      @completed="handleUploadImgs"
      :uploadIdlist="uploadIdlist"
    ></imgsUpload>
  </div>
</template>

<script>
import moment from 'moment'
import BillEditor from '../../../components/bill-editor/index'
import InfoModel from '../../components/infomodel/index'
import SplitBill from '../../components/splitBill'
import modelConfig from './config/model/index'

import ViewSupplier from '../../components/viewSupplier'
import ViewCommodity from '../../components/viewCommodity'
import LoginModal from '../../components/login-modal'

import { detailConfig } from './config/detail'
import { splitColumns } from './config/split/columns'
import { splitFormItems } from './config/split/formitems'
import { addItem } from './api'
import { footerItem } from './config/detail/footer'
import Editor from '../../../basedata/goodsManager/editor'

import { showStockCountModual } from '../../mixins/showStockCount'
import { getDicsModual } from '../../mixins/getDics'
import { receiveSplitModule } from '../../mixins/receiveSplit'
import { receiveExtendInfoModule } from '../../mixins/receiveExtendInfo'
import { getExpiredDaysModual } from '../../mixins/getExpiredDays'
import { extractAfterModule } from '../../mixins/extractAfter'
import { businessRuleModule } from '../../mixins/rule'
import { doubleRcvModule } from '../../mixins/doubleRcv'
import ImgsUpload from '@/views/kzyWMS/components/ImgsUpload'

import { splitModule } from '../../receive/rcvEditor/mixins/split'

import { aa } from './mock'
// import { handleExpiredDays } from "../../config/utils";
import {
  handleShowProductionDate,
  handleShowExpiredDate,
  handleExpiredDays,
} from '../../receive/rcvEditor/script/lineHandleLogic'
import { validateModule } from '../../receive/rcvEditor/mixins/validate'
import { itemsColChangeModule } from '../../receive/rcvEditor/mixins/itemsColChange'
import { createValidator } from '../../../utils/validator'
import { getBusiness } from '@/views/kzyWMS/api/business' // 系统参数接口

export default {
  components: {
    'bill-editor': BillEditor,
    'info-model': InfoModel,
    'split-bill': SplitBill,
    'view-supplier': ViewSupplier,
    'view-commodity': ViewCommodity,
    'c-cditor': Editor,
    'login-modal': LoginModal,
    imgsUpload: ImgsUpload,
  },

  mixins: [
    showStockCountModual,
    getDicsModual,
    // receiveSplitModule,
    receiveExtendInfoModule,
    getExpiredDaysModual,
    validateModule,
    extractAfterModule,
    itemsColChangeModule,
    businessRuleModule,
    doubleRcvModule,
    splitModule,
  ],

  data() {
    return {
      businessData:null,
      mainlist: null,
      sublist: null,
      modelConfig: modelConfig(this),
      detailtList: null,
      detailData: null,
      visible: false,
      splitColumns: splitColumns,
      splitFormItems: splitFormItems,
      buildingList: [],
      dics: {},
      items: footerItem,
      show: true,
      showViewSupplier: false,
      viewSupplierItem: null,
      showCommodity: false,
      viewCommodity: null,
      expiredDays: { intercept: 90, alert: 180 },
      maintainVisible: false,
      detailItem: null,
      isUpload: false,
      lookats: false,
      uploadIdlist: [],
      createValidator: createValidator([
        this.validateNotEmpty,
        this.validateStockStatusContainer,
        this.validateCaseOrPiece,
        this.validateStockStatus,
        // this.validateExpiredDays,销退去掉近效期拦截
        this.validateStoreTemperature,
        this.validateBatchExpiredDate,
        this.validateStockStatusTemperature,
        this.container,
      ]),
    }
  },

  created() {
    getBusiness().then((res) => {
      this.businessData = res // 系统参数
      console.log(this.businessData,'系统参数');
      this.execute(detailConfig(this)).then((list) => {
        this.detailtList = list
      })
    })
    // setTimeout(() => {
    //   this.setinfo(null,aa)
    // }, 3000);
  },

  methods: {
    queryRefFromName(name) {
      return this.$refs.detail.$refs[name][0]
    },

    setinfo(a, data) {
      if (data) {
        this.mainlist = data.mainlist
        this.sublist = data.sublist
        let info = {
          main: {
            ...data.mainlist[0],
            shipArriveTime: moment().format('YYYY-MM-DD HH:mm:ss'),
            rcvDate: moment().format('YYYY-MM-DD HH:mm:ss'),
            executorUser: this.$store.state.user.name,
          },
          extend: { ...data.mainlist[0] },
          operate: {},
          list: data.sublist.map((tt) => {
            let pieceQty = tt.conversionRate * (+tt.oddCaseQty || 0) + (+tt.oddPieceQty || 0)
            // let batchProductionDate = tt.batchProductionDate ? tt.batchProductionDate.substring(0, 10) : ''
            // let batchExpiredDate = tt.batchExpiredDate ? tt.batchExpiredDate.substring(0, 10) : ''
            // let showProductionDate = batchProductionDate.replace(/-/g, '')
            // let showExpiredDate = batchExpiredDate.replace(/-/g, '')
            let batchProductionDate = tt.showProductionDate ? handleShowProductionDate(tt.showProductionDate) : ''
            let batchExpiredDate = tt.showExpiredDate
              ? handleShowExpiredDate(tt.showExpiredDate, tt.shelfLifeUnit, +tt.shelfLifeNum)
              : ''
            return {
              ...tt,
              asnLineId: tt.asnLineId + '_cus_' + Math.floor(Math.random() * 1000), //暂存后 拆分可能重复
              mtlOwnerId: data.mainlist[0].mtlOwnerId,
              showProductionDate: tt.showProductionDate,
              showExpiredDate: tt.showExpiredDate,
              batchProductionDate: batchProductionDate,
              batchExpiredDate: batchExpiredDate,
              itemHealthIsDouble: tt.itemHealthIsDouble || '0',
              qty: (pieceQty / tt.conversionRate).toFixed(2),
              pieceQty: pieceQty,
              oldPieceQty: pieceQty,
              // 冷藏 2~8   冷冻 -10~-1
              tempControlScope: tt.tempControlScope
                ? tt.tempControlScope
                : tt.storeTemperature == '冷藏'
                ? '2~8'
                : tt.storeTemperature == '冷冻'
                ? '-10~-1'
                : null,
              rcvType: data.mainlist[0].rcvType, //入库类型
            }
          }),
        }
        info.list.forEach((t) => {
          let expiredDate = new Date(t.batchExpiredDate)
          expiredDate.setHours(0)
          console.log(t.batchExpiredDate, 'expiredDate')
          //有效期小于当前日期|| 有效期至为null，结论默认null
          if (expiredDate < new Date() || !t.batchExpiredDate) {
            t.stockStatus = ''
          } else {
            t.stockStatus = '0'
          }
        })
        this.detailData = info
        console.log(this.detailData ,'52222222');
        // this.getBuildingList()
        this.getBilldRcvreason1()
        this.getDefReason()
        this.getReturnType()
        this.getHandlingMeasure()
        this.getExpiredDays(data.mainlist[0].warehouseId)
        this.showStockCount(info.list[0].itemId)
        this.receiveSetValueAfter(info.list)
      }
    },

    submitData() {
      this.getDetailData().then((params) => {
        var aa = 0
        if (!params) {
          return
        }
        if (aa == 1) {
          return
        }
        let toSave = () => {
          this.$confirm({
            content: this.$lang('是否确定保存?'),
            onOk: () => {
              return this.handleAdd(params)
            },
          })
        }
        this.validateShipFromDate(params, () => {
          // 双人收货
          this.handleDoubleRcv(params, () => {
            this.validateManufacturerLotNum(params, toSave)
          })
        })
      })
    },

    getDetailData(isValidate = true, isSelected = true) {
      return this.$refs.detail.getDetailData(isValidate, isSelected).then((vals) => {
        return this.createValidator.execute(vals, { notValid: !isValidate }).then((res) => {
          console.log(res, 'res')
          if (res)
            return {
              rcvHeadersDTO: {
                ...vals.main,
                caseQty: '1',
                pieceQty: '1',
                autoBillNum: +new Date() + '',
                shipArriveTime: moment(vals.main.shipArriveTime).format('YYYY-MM-DD HH:mm:ss'),
                rcvDate: moment(vals.main.rcvDate).format('YYYY-MM-DD HH:mm:ss'),
              },
              rcvHeadersProfilesDTO: { ...this.mainlist[0], ...vals.extend },
              rcvHeadersSrcBillsDTOList: [
                {
                  ...this.mainlist[0],
                  srcHeaderType: vals.main.srcBillType,
                  srcAutoBillNum: vals.main.srcAutoBillNum,
                  rcvDate: vals.main.rcvDate,
                },
              ],
              rcvLinesDTOList: vals.list.map((tt, ii) => {
                // 拆单
                let asnLineId = tt.asnLineId.replace(/_cus_\d*/g, '')
                let rcvLinesProfilesDTO = this.sublist.find((ttt) => ttt.asnLineId == asnLineId)
                rcvLinesProfilesDTO.lineNum = ii + 1
                var _batchId = null
                var _batchNum = null
                if (vals.main.inventoryOpType === '1') {
                  _batchId = tt.batchId
                  _batchNum = tt.batchNum
                } else {
                  if (tt.manufacturerLotNum == tt.manufacturerLotNumOld) {
                    _batchId = tt.batchId
                    _batchNum = tt.batchNum
                  }
                }
                return {
                  ...tt,
                  asnLineId: asnLineId,
                  lineNum: ii + 1,
                  mtlOwnerName: vals.main.mtlOwnerName,
                  warehouseName: vals.main.warehouseName,
                  srcBillType: vals.main.srcBillType,
                  rcvLinesProfilesDTO: rcvLinesProfilesDTO,
                  rcvType: this.mainlist[0].rcvType,
                  // showProductionDate: tt.showProductionDate,
                  // showExpiredDate: tt.showExpiredDate,
                  batchProductionDate: tt.batchProductionDate ? tt.batchProductionDate + ' 00:00:00' : '',
                  batchExpiredDate: tt.batchExpiredDate ? tt.batchExpiredDate + ' 00:00:00' : '',
                  rcvLinesPicDTOList: tt.rcvLinesPicDTOList
                    ? tt.rcvLinesPicDTOList.split(',').map((t) => ({ picFileurl: t }))
                    : null,

                  batchId: _batchId,
                  batchNum: _batchNum,
                  // batchNum:  vals.maininventoryOpType ==='0' && tt.manufacturerLotNum == tt.manufacturerLotNumOld ? tt.batchNum : null,
                  // batchId: tt.manufacturerLotNum == tt.manufacturerLotNumOld ? tt.batchId : null,
                }
              }),
            }
          return res
        })
      })
    },

    validateNotEmpty(params) {
      return new Promise((resolve) => {
        console.log(params, resolve, '请输入必填项')
        if (!params) {
          this.$message.warning('请输入必填项')
          resolve(false)
          return false
        }
        if (!Array.isArray(params.list) || params.list.length === 0) {
          this.$message.warning('请选择要提交的明细')
          resolve(false)
          return false
        }
        resolve(true)
      })
    },

    handleAdd(params) {
      return addItem(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.items.forEach((tt, i) => {
          tt.value = null
        })
        this.$message.success(this.$lang('新增成功'))
        this.handleReset()
      })
    },

    handleReset() {
      this.detailData = null

      this.viewSupplierItem = null
      this.viewCommodity = null
    },

    /* 商品维护 */
    handleOk(e) {
      this.$refs.itemsEditor.getDetailData()
    },
    handleCancel(e) {
      this.maintainVisible = false
    },
    handleItemsComplete() {
      this.maintainVisible = false
    },
    showMaintain() {
      let ref = this.queryRefFromName('list')
      let val = ref.data.find((t) => ref.selectedRowKeys.some((tt) => tt == t.asnLineId))
      if (!val) {
        this.$message.warning('请勾选需要维护的商品项')
        return
      }
      this.detailItem = { itemId: val.itemId }
      this.maintainVisible = true
    },

    // 上传逻辑
    showUploadImgs(record, index, dataSource) {
      if (record.rcvLinesPicDTOList) {
        this.uploadIdlist = record.rcvLinesPicDTOList.split(',')
      }
      this.uploadItemIndex = { record, index, dataSource }
      this.isUpload = true
    },

    handleUploadImgs(list) {
      // 拆分后的同一类明细，上传图片数据要一致
      let rcvLinesPicDTOList = list.map((t) => t.id).join(',')
      let asnLineId = this.uploadItemIndex.record.asnLineId
      asnLineId = asnLineId.replace(/_cus_\d*/g, '')
      this.uploadItemIndex.dataSource.forEach((tt) => {
        if (tt.asnLineId.indexOf(asnLineId) >= 0) {
          tt.rcvLinesPicDTOList = rcvLinesPicDTOList
        }
      })
    },
  },
}
</script>

<style lang="less" scoped >
.footer {
  margin-top: 50px;
  bottom: 0px;
}
.footer_bat {
  background-color: #feffe0;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.1);
  padding: 20px;
}
.footer_bat-item {
  display: inline-block;
  width: 25%;
  min-width: 180px;
  font-size: 14px;
  // color: #2b80ff;
  font-weight: bold;
  .numClass {
    font-size: 20px;
    color: #2b80ff;
    padding-left: 8px;
  }
}
</style>