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

    <info-model ref="infoModel" v-model="visible" :config="config" @change="setinfo" />

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

    <spot-check v-model="spotVisible" ref="data" :dataList="spotData" v-on:isSpotCheck="isSpotCheckNum"></spot-check>

    <scan-code v-model="scanVisible" ref="scan" :scanTable="scanTableList"></scan-code>

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

    <view-supplier v-model="showViewSupplier" :item="viewSupplierItem" />
    <view-update v-model="showUpdate" :item="viewUpdate" />
  </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 config from './config/model'
import { detailConfig } from './config/detail'
import { rcvTypeOptions } from '../../../config/options'
import { splitColumns } from './config/split/columns'
import { splitFormItems } from './config/split/formitems'
import spotCheck from './components/spotCheck.vue'
import scanCode from './components/scanCode'
import { addItem, taskSplit, doException, getPreList, getDicts, isSupervised, getHostRqcResult } from './api'
import ViewSupplier from '../../../components/viewSupplier'
import ViewCommodity from '../../../components/viewCommodity'
import viewUpdata from '../../../components/viewUpdata'
import { toPrintServer, tempType } from '../../../../utils/printServer'
import { businessRuleModule } from '../../../mixins/rule'
import { getBusiness } from '@/views/kzyWMS/api/business' // 系统参数接口
import { createValidator } from '../../../../utils/validator'

import { a } from './mock'

export default {
  components: {
    'bill-editor': BillEditor,
    'info-model': InfoModel,
    'spot-check': spotCheck,
    'split-bill': SplitBill,
    'scan-code': scanCode,
    'view-supplier': ViewSupplier,
    'view-commodity': ViewCommodity,
    'view-update': viewUpdata,
  },
  mixins: [businessRuleModule],
  props: {
    isView: {
      type: Boolean,
      default: false,
    },
  },

  data() {
    return {
      businessData: null,
      mainlist: [],
      sublist: [],
      config: config(this),
      detailtList: null,
      detailData: null,
      visible: false,
      splitVisible: false,
      splitColumns: splitColumns,
      splitFormItems: splitFormItems,
      splitOriginItem: null,
      spotVisible: false,
      confirmLoading: false,
      spotData: [],
      scanVisible: false,
      scanTableList: [],
      showViewSupplier: false,
      viewSupplierItem: null,
      showCommodity: false,
      viewCommodity: null,
      showUpdate: false,
      viewUpdate: null,
      isSpotCheck: false,
      selectedRows: [],
      stockStatus: null, //验收结论
      createValidator: createValidator([this.validateNotEmpty]),
    }
  },

  created() {
    getBusiness().then((res) => {
      this.businessData = res // 系统参数
      console.log(this.businessData, 'this.businessData')
      this.handleView()
      this.execute(detailConfig(this)).then((list) => {
        this.detailtList = list
      })
    })
    // this.getHostRqcResult()
  },

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

    setinfo(a, data) {
      if (!data) return
      this.mainlist = data.mainlist
      this.sublist = data.sublist
      let info = {
        main: {
          ...data.mainlist[0],
          qcOperator: this.$store.state.user.name,
          rcvTypet: rcvTypeOptions.find((t) => t.value == data.mainlist[0].rcvType).title,
          // rcvDate: data.mainlist[0].rcvDate.substring(0, 10),
        },
        extend: { ...data.mainlist[0] },
        operate: {},
        list: data.sublist.map((t) => {
          let pieceQty = t.conversionRate * (+t.oddCaseQty || 0) + (+t.oddPieceQty || 0)
          let batchProductionDate = t.batchProductionDate ? t.batchProductionDate.substring(0, 10) : ''
          let batchExpiredDate = t.batchExpiredDate ? t.batchExpiredDate.substring(0, 10) : ''
          // let showProductionDate = batchProductionDate.replace(/-/g, '')
          // let showExpiredDate = batchExpiredDate.replace(/-/g, '')
          let whAreaCategoryCode = ''
          // 3.直调库 只能订单类型是直调的选，即订单类型是直调的默认并且只能入直调库
          if (data.mainlist[0].rcvType == '7') {
            whAreaCategoryCode = 'ZDK'
          }
          // 13.代管库 只能订单类型是代管的才可以入到代管库，即订单类型是代管的默认并且只能入代管库
          else if (data.mainlist[0].rcvType == '8') {
            whAreaCategoryCode = 'DGK'
          }
          // 10.整散合一库 只能入整散合一的商品，即整散合一的商品默认并且只能入整散合一库
          else if (t.itemHealthStoreCategory.indexOf('合一') >= 0) {
            whAreaCategoryCode = 'HYK'
          }
          return {
            ...t,
            qcOpcode1: this.$store.state.user.name,
            qcOddCaseActQty: t.caseQty,
            qcOddPieceActQty: t.oddPieceQty,
            // showExpiredDate: showExpiredDate,
            // showProductionDate: showProductionDate,
            batchProductionDate: batchProductionDate,
            batchExpiredDate: batchExpiredDate,
            srcAutoBillNum: data.mainlist[0].srcAutoBillNum,
            rcvType: data.mainlist[0].rcvType,
            qty: (pieceQty / t.conversionRate).toFixed(2),
            pieceQty: pieceQty,
            oldPieceQty: pieceQty,
            // 收货的时候 结论为收货 到质检那里都是合格 结论为待处理 到质检那里是待处理
            qcResult1: typeof t.result === 'string' ? t.result.trim() : null, //默认值参考收货结论
            // qcResult1: this.stockStatus,
            whAreaCategoryCode: t.whAreaCategoryCode || whAreaCategoryCode,
            rqcReportNoNew: t.rqcReportNo, //用来判断报告单号是否可编辑
          }
        }),
      }
      let rqcUser = this.$store.state.user.name
      info.main.rqcUser = rqcUser
      this.detailData = info
      this.isSpotCheck = false
    },

    showSplitBill(item) {
      this.splitOriginItem = this.detailData.list.find((t) => t.taskRqcId == item.taskRqcId)
      this.splitVisible = true
    },

    validateNotEmpty(params) {
      console.log(params,'paramsparams');
      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) => {
        if (!params) {
          return
        }
        if (!this.isSpotCheck) {
          this.getList()
          return
        }
        let list = params.rqcLinesDTOList
        this.isCode(list, () => {
          this.$confirm({
            content: this.$lang('是否确定提交?'),
            onOk: () => {
              return this.handleAdd(params)
            },
          })
        })
      })
    },

    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 {
              rqcHeadersDTO: {
                ...vals.main,
                rcvDate: moment(vals.main.rcvDate).format('YYYY-MM-DD HH:mm:ss'),
              },
              rqcLinesDTOList: vals.list.map((t) => ({
                ...t,
                oddCaseQty: t.caseQty,
                rcvType: this.mainlist[0].rcvType,
                stockStatus: t.qcResult1,
              })),
            }
          return res
        })
      })
    },
    isSpotCheckNum(data) {
      this.isSpotCheck = data
    },
    // 是否完成扫描监管码
    isCode(list, callback) {
      // refBillId\refBillLineId
      let ref = []
      list.forEach((t) => {
        if (t.isSupervise === 1) {
          ref.push({
            refBillId: t.rcvHeaderId,
            refBillLineId: t.rcvLineId,
            warehouseId: t.warehouseId,
          })
        }
        return
      })
      if (ref.length > 0) {
        isSupervised(ref).then((res) => {
          if (!res.data) {
            this.scanCode()
            return
          }
          callback()
        })
      } else {
        callback()
      }
    },

    handleView() {
      let arr = detailConfig(this)
      if (this.isView) {
        arr.forEach((t) => {
          t.list.forEach((tt) => {
            if (tt.item.type === 'p-grid-form') {
              tt.item.config = tt.item.config.map((t) => ({ ...t, disabled: true, placeholder: '' }))
            } else if (tt.item.type === 'p-table-edit') {
            }
          })
        })
      }
      this.detailtList = arr
    },

    splitedCallback(item) {
      item.pieceQty = item.conversionRate * item.caseQty + item.oddPieceQty
      item.qty = (item.pieceQty / item.conversionRate).toFixed(2)
    },

    handleSpliteOk(list) {
      let nList = list.map((t, i) => ({
        ...this.splitOriginItem,
        ...t,
        taskRqcId: i == 0 ? this.splitOriginItem.taskRqcId : null,
      }))
      this.handleSplitBill(nList)
    },

    toErrorBill() {
      let ref = this.queryRefFromName('list')
      if (ref.selectedRowKeys.length === 0) {
        this.$message.warning(this.$lang('请先勾选'))
        return
      }
      this.$confirm({
        content: this.$lang('是否确定提交?'),
        onOk: () => {
          let params = ref.data.filter((t) => ref.selectedRowKeys.some((k) => k == t[ref.rowKey]))
          return this.handleErrorBill(params).then((res) => {
            if (!res) return
            ref.data = ref.data.filter((t) => !ref.selectedRowKeys.some((k) => k == t[ref.rowKey]))
            ref.selectedRowKeys = []
          })
        },
      })
    },
    //批量不合格
    batchFailure() {
      let ref = this.queryRefFromName('list').data
      ref.forEach((tt) => {
        tt.qcResult1 = '1'
      })
    },

    handleAdd(params) {
      const isPrint = +params.rqcHeadersDTO.isInstockPrint
      return addItem(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.handleReset()
        //itemHealthIsDouble 双人业务类型(0:正常 1：双人验收，默认正常)
        params.rqcLinesDTOList.forEach((tt, i) => {
          if (tt.itemHealthIsDouble === 1) {
            // 商品需要双人验收时，第一次验收需要进行提示
            if (tt.times === 0) {
              this.$message.warning(this.$lang(`第${i + 1}行商品需双人验收`))
            }
          }
        })
        if (isPrint === 0) {
          this.$message.success(this.$lang('新增成功'))
          return
        }
        if (!res.data || !res.data.data) {
          this.$message.warning(this.$lang('当前没有需要进行打印的任务'))
        } else {
          const printParms = {
            consignorId: params.rqcHeadersDTO.mtlOwnerId,
          }
          const warehouseId = params.rqcHeadersDTO.warehouseId
          var temp = tempType.SJ_BQ
          if (res.data.tempType) {
            temp = res.data.tempType
          }
          //调用打印方法()
          toPrintServer(res.data.data, warehouseId, temp, printParms).then((res) => {
            if (!res.success) {
              this.$exception(res)
              return
            }
            this.$message.success(res.message)
          })
        }
        return false
      })
    },

    handleReset() {
      this.detailData = null
      this.viewCommodity = null
      this.viewSupplierItem = null
      this.viewUpdate = null
      this.isSpotCheck = false
    },

    handleSplitBill(params) {
      this.confirmLoading = true
      return taskSplit(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.$message.success(this.$lang('拆单成功'))
        this.splitVisible = false
        this.confirmLoading = false
        let newBills = params.map((t, i) => ({
          ...t,
          qcOpcode1: this.$store.state.user.name,
          qcOddCaseActQty: t.caseQty,
          qcOddPieceActQty: t.oddPieceQty,
          srcAutoBillNum: this.mainlist[0].srcAutoBillNum,
          taskRqcId: res.data[i],
        }))
        let id = this.splitOriginItem.taskRqcId
        let list = this.detailData.list
        list.splice(
          this.detailData.list.findIndex((t) => t.taskRqcId == id),
          1,
          ...newBills
        )
        this.detailData = {
          ...this.detailData,
          list: [...list],
        }
      })
    },

    handleErrorBill(params) {
      return doException(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return false
        }
        this.$message.success(this.$lang('操作成功'))
        return true
      })
    },
    //抽检
    getList() {
      this.queryRefFromName('list')
        .getDataSource(this.selectedRows.length == 0 ? false : true, false)
        .then((vals) => {
          if (!vals.length) {
            this.$message.error('请先选择单据再进行抽检操作')
            return
          }
          this.getCheck(vals)
        })
    },
    getCheck(data) {
      let result = []
      data.forEach((t) => {
        if (t.qcResult1 === '3') {
          return
        }
        result.push(t)
      })
      if (result.length === 0) {
        this.$message.error('该单据不需要进行抽检操作')
        return
      }
      this.spotVisible = true
      getPreList(
        result.map((t) => ({
          ...t,
          oddCaseQty: t.caseQty,
        }))
      ).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.spotData = res.data
      })
    },
    //扫描监管码
    scanCode() {
      this.queryRefFromName('list')
        .getDataSource(this.selectedRows.length == 0 ? false : true, false)
        .then(async (vals) => {
          if (!vals.length) {
            this.$message.error('请先选择单据再操作扫描药品追溯码')
            return
          }
          if (vals.length < 1) {
            let list = vals.filter((tt) => tt.isSupervise == 1)
            this.scanTableList = [...list]
            this.scanVisible = true
            return
          }
          let list = vals.filter((tt) => tt.isSupervise == 1)
          this.scanTableList = [...list]
          this.scanVisible = true
        })
    },
    //点击明细弹扫描监管码
    codeModal(data) {
      this.scanTableList = [data]
      this.scanVisible = true
    },
  },
}
</script>

<style></style>
