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

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

    <!-- history -->
    <info-model ref="historyModel" v-model="showHistoryModal" :config="historyConfig" @change="getHistory" />

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

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

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

    <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>

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

    <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>
  </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 ViewSupplier from '../../components/viewSupplier'
import ViewCommodity from '../../components/viewCommodity'
import ImgsUpload from '@/views/kzyWMS/components/ImgsUpload'
import Editor from '../../../basedata/goodsManager/editor'

import modelConfig from './config/model/index'
import { detailConfig } from './config/detail'
import { footerItem } from './config/detail/footer'
import historyConfig from './config/history'

import { splitColumns } from './config/split/columns'
import { splitFormItems } from './config/split/formitems'

import { extendInfoModule } from './mixins/extendInfo'
import { historyModule } from './mixins/history'
import { validateModule } from './mixins/validate'
import { itemsColChangeModule } from './mixins/itemsColChange'
import { showStockCountModual } from '../../mixins/showStockCount'
import { getDicsModual } from '../../mixins/getDics'
import { receiveSplitModule } from '../../mixins/receiveSplit'
import { getExpiredDaysModual } from '../../mixins/getExpiredDays'
import { extractAfterModule } from '../../mixins/extractAfter'
import { businessRuleModule } from '../../mixins/rule'
import { addItem, getItem, postAsnClear } from './api'
import { aa } from './mock'
import { createValidator } from '../../../utils/validator'
import { splitModule } from './mixins/split'
import { getBusiness } from '@/views/kzyWMS/api/business' // 系统参数接口


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

  mixins: [
    extendInfoModule,
    // receiveSplitModule,
    splitModule,
    historyModule,
    validateModule,
    itemsColChangeModule,
    showStockCountModual,
    getDicsModual,
    getExpiredDaysModual,
    extractAfterModule,
    businessRuleModule,
  ],

  data() {
    return {
      businessData: null,
      mainlist: null,
      sublist: null,
      modelConfig: modelConfig(this),
      detailtList: null,
      detailData: null,
      visible: false,
      buildingList: [],
      items: footerItem,
      show: true,
      maintainVisible: false,
      detailItem: null,
      expiredDays: { intercept: 90, alert: 180 },
      isUpload: false,
      lookats: false,
      uploadItemIndex: null,
      showViewSupplier: false,
      viewSupplierItem: null,
      showCommodity: false,
      viewCommodity: null,
      historyConfig: historyConfig(this),
      showHistoryModal: false,
      splitColumns: splitColumns,
      splitFormItems: splitFormItems,
      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 // 系统参数
      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.$refs.detail.resetData()
        this.mainlist = data.mainlist
        this.sublist = data.sublist
        let info = {
          main: {
            ...data.mainlist[0],
            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, '')
            return {
              ...tt,
              asnLineId: tt.asnLineId + '_cus_' + Math.floor(Math.random() * 1000), //暂存后 拆分可能重复
              stockStatus: tt.stockStatus ? tt.stockStatus : '0', // 默认收货
              mtlOwnerId: data.mainlist[0].mtlOwnerId,
              rcvType:data.mainlist[0].rcvType,
              showProductionDate: showProductionDate,
              showExpiredDate: 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 == '冷冻'
                ? '-100~-1'
                : null,
            }
          }),
        }
        //  if (this.businessData == 'kzy') {
        //    info.list.forEach((t)=>{
        //      t.stockStatus = ''
        //    })
        //  }
        this.detailData = info
        console.log(this.detailData,'this.detailData');
        this.getExpiredDays(data.mainlist[0].warehouseId)
        this.showStockCount(info.list[0].itemId)
        this.getBilldRcvreason1()
        this.getDefReason()
        this.receiveSetValueAfter(info.list)
      }
    },

    validateNotEmpty(params) {
      return new Promise((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)
      })
    },
    
    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.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) => {
          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
                let bldg = tt.bldgId ? this.buildingList.find((t) => t.bldgId == tt.bldgId) : null
                return {
                  ...tt,
                  asnLineId: asnLineId,
                  lineNum: ii + 1,
                  mtlOwnerName: vals.main.mtlOwnerName,
                  warehouseName: vals.main.warehouseName,
                  srcBillType: vals.main.srcBillType,
                  rcvLinesProfilesDTO: rcvLinesProfilesDTO,
                  bldgName: bldg ? bldg.bldgName : '',
                  bldgCode: bldg ? bldg.bldgCode : '',
                  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,
                  batchNum: tt.manufacturerLotNum == tt.manufacturerLotNumOld ? tt.batchNum : null,
                  batchId: tt.manufacturerLotNum == tt.manufacturerLotNumOld ? tt.batchId : null,
                }
              }),
            }
          return res
        })
      })
    },

    validateSubmit(params) {
      if (!params) {
        this.$message.warning('请输入必填项')
        return false
      }
      if (!Array.isArray(params.list) || params.list.length === 0) {
        this.$message.warning('请选择要提交的明细')
        return false
      }
      return 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()
        this.items.forEach((tt) => {
          tt.value = ''
        })
      })
    },

    handleReset() {
      this.detailData = null
      this.splitOriginItem = null
      this.detailItem = null
      // this.rcvItemLotNumList.clear();
      this.viewSupplierItem = null
      this.viewCommodity = null
      this.mainlist = null
      this.sublist = 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
        }
      })
    },


    // 清理过期
    handleAsnClear(items) {
      this.$confirm({
        content: this.$lang('是否确定清理此过期订单?'),
        onOk: () => {
          let ids = items.map((tt) => tt.asnHeaderId)
          return postAsnClear(ids).then((res) => {
            if (!res.success) {
              this.$exception(res)
              return
            }
            this.$refs.detailModel.reloadMain()
            this.$message.success('清理过期订单成功')
          })
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
.footer {
  margin-top: 50px;
  bottom: 0px;
}
.footer_bat {
  background-color: #feffe0; // #f0f8ff;
  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>
