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

<script>
import DetailPage from '../components/bill-editor/index'
import { detailConfig } from './config/moveStocker'
import { moveAdd, queryMovePrintList } from '../api/api'
import { getCargoOwner } from '../../utils/index'
import { toPrintServer } from '@/views/kzyWMS/utils/printServer.js'

export default {
  components: { DetailPage },
  props: {
    detailItem: {
      type: Object,
      default: null,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isReady: false,
      detailtList: null,
      detailData: null,
      visible: false,
      dcId: '', // 仓配中心id
      remoteParams: {},
      formsVal: {},
      tiemID: null,
    }
  },

  created() {
    this.handleView()
    this.getAuthBycargoOwner()
  },
  mounted() {
    let user = this.$store.state.user
    console.log(user, 'useruseruseruseruser')
    let warehouse = this.$store.state.user.warehouse
    let today = new Date()
    let tYear = today.getFullYear()
    let tMonth = today.getMonth() + 1
    let tDate = today.getDate()
    let day = tYear + '-' + tMonth + '-' + tDate
    this.queryRefFromName('main').form.setFieldsValue({
      today: day,
      warehouseName: warehouse.warehouseName,
      warehouseId: warehouse.warehouseId,
      enterpriseName: user.info.enterpriseName,
      warehouseWorkerId: user.info.userId,
      warehouseWorkerName: user.info.username,
      departmentId: user.info.organizations ? (user.info.organizations[0] ? user.info.organizations[0].id : '') : '',
      departmentName: user.info.organizations
        ? user.info.organizations[0]
          ? user.info.organizations[0].name
          : ''
        : '',
    })
    this.remoteParams.warehouseId = warehouse.warehouseId
  },
  methods: {
    toBack() {
      this.$emit('changeStep', { step: 1, item: null })
    },
    queryRefFromName(name) {
      return this.$refs.detail.$refs[name][0]
    },
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.queryRefFromName('main').form.setFieldsValue({
              cargoOwnerId: res.data.list[0].companyId,
              cargoOwnerName: res.data.list[0].companyName,
              cargoOwnerCode: res.data.list[0].companyCode,
            })
          })
        }
        if (!res.success) {
          this.$exception(res)
          return
        }
      })
    },
    getData() {
      return queryItem({ itemId: this.detailItem.itemId }).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        let d = { main: {} }
        Object.keys(res.data).forEach((k) => {
          if (res.data[k] === null) {
            // d.main[k] = res.data[k];
            d.main[k] = ''
          } else if (typeof res.data[k] === 'object') {
            d[k] = res.data[k]
          } else {
            d.main[k] = res.data[k]
          }
        })
        this.detailData = d
      })
    },

    getDetailData() {
      let vals = this.$refs.detail.getDetailData()
      let main = vals.main
      delete vals.main
      let params = { ...main, ...vals }
      // console.log('vals', vals);
      if (!vals) {
        return
      }
      if (this.detailItem) {
        this.$confirm({
          content: this.$lang('是否提交修改?'),
          onOk: () => {
            return this.handleUpload(params)
          },
        })
      } else {
        this.$confirm({
          content: this.$lang('是否确定提交?'),
          onOk: () => {
            return this.handleAdd(params)
          },
        })
      }
    },
    saveData(datas) {
      datas
        .then((val) => {
          console.log(val, 'valvalval')
          if (Array.isArray(val) && val.length < 1) return this.$message.warn('请选择商品')
          let datas = val
          let vals = this.$refs.detail.getDetailData()
          let main = vals.main
          let params = {
            moveDetails: datas,
            ...main,
            lkFlag: 'Y',
            dcId: this.dcId,
          }
          moveAdd(params).then((res) => {
            if (!res.success) {
              return this.$exception(res)
            }
            this.printMove(params)
            this.$message.success('保存成功')
            this.$refs.detail.$refs['baseMtlItemUomConversionsList'][0].delItems()
          })
        })
        .catch((error) => {
          this.$message.error(error[0]?.errors[0]?.field + error[0]?.errors[0]?.message)
        })
    },
    printMove(params) {
      // 移库单打印
      queryMovePrintList(params).then((res) => {
        if (!res.success) {
          return this.$exception(res)
        }
        toPrintServer(res.data, params.warehouseId, '移库单打印模板').then((t) => {
          if (!t.success) {
            this.$exception(t)
            return
          }
          this.$message.success(t.message)
        })
      })
    },
    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
    },
    handleAdd(params) {
      return addItem(params).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        this.$message.success(this.$lang('新增成功'))
        this.toBack()
      })
    },
    handleUpload(params) {
      params.itemId = this.detailItem.itemId
      return uploadItem(params).then((res) => {
        if (!res.success) {
          this.$message.error(res.message)
          return
        }
        this.$message.success(this.$lang('新增成功'))
        this.toBack()
      })
    },
  },
}
</script>

<style></style>
