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

<script>
import DetailPage from '@/views/kzyWMS/bound/components/bill-editor/index'
import { detailConfig } from './config/index'
import { postline, confirmWaveBill } from './api/api'
import { getCargoOwner } from '../../utils/index'

export default {
  components: { DetailPage },
  props: {
    detailItem: {
      type: Object,
      default: null,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isReady: false,
      detailtList: null,
      spinning: false,
      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: {
    queryDetailList() {
      // 查询明细
      let mainVals = this.queryRefFromName('main').form.getFieldsValue()
      let params = {
        num: 'billTemporaryPageList',
        pageNum: 1,
        pageSize: 1000,
        params: { ...mainVals },
      }
      this.spinning = true
      postline(params).then((res) => {
        this.spinning = false
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.queryRefFromName('baseMtlItemUomConversionsList').setDataSourceAll(res.data ? res.data.list : [])
      })
    },
    querydetailData(record, checkedStatus) {
      // 查询明细
      if (!checkedStatus) {
        this.queryRefFromName('baseMtlItemUomConversionsList1').setDataSourceAll([])
        return
      }
      let params = {
        num: 'billTemporaryDetailsPageList',
        pageNum: 1,
        pageSize: 1000,
        params: { billId: record.id },
      }
      this.spinning = true
      postline(params).then((res) => {
        this.spinning = false
        if (!res.success) {
          this.$exception(res)
          return
        }
        this.queryRefFromName('baseMtlItemUomConversionsList1').setDataSourceAll(res.data.list)
      })
    },
    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('请选择主表数据')
          if (val.length == 1) {
            // 主表只有一个的时候 可以维护明细表数据
            this.queryRefFromName('baseMtlItemUomConversionsList1')
              .getFieldsValue(true)
              .then((detailsData) => {
                // 选中明细表
                if (Array.isArray(detailsData) && detailsData.length < 1) {
                  this.$confirm({
                    title: '是否确认保存',
                    content: this.$lang('您还未勾选明细表数据是否直接保存主表数据?'),
                    onOk: () => {
                      this.saveCommit(val)
                    },
                  })
                } else {
                  // 保存明细
                  val.items = detailsData
                  this.$confirm({
                    content: this.$lang('是否确认保存?'),
                    onOk: () => {
                      this.saveCommit(val)
                    },
                  })
                }
              })
          } else {
            // 大于1条主表数据就直接保存主表数据
            this.$confirm({
              content: this.$lang('是否确认保存?'),
              onOk: () => {
                this.saveCommit(val)
              },
            })
          }
        })
        .catch((error) => {
          this.$message.error(error[0]?.errors[0]?.field + error[0]?.errors[0]?.message)
        })
    },
    saveCommit(params) {
      confirmWaveBill(params).then((res) => {
        if (!res.success) {
          return this.$exception(res)
        }
        this.$message.success('出库确认成功')
        this.queryDetailList()
        this.queryRefFromName('baseMtlItemUomConversionsList1').setDataSourceAll([])
      })
    },
    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>
.dropdownClassName1 {
  left: auto !important;
  right: 50px !important;
}
</style>
