<template>
  <div>
    <p-spin :spinning="spinning">
      <!-- <p-card :title="title">
      <div slot="extra">
        <div class="btns">
          <p-button v-if="!keyType" @click="handleOk">保存</p-button>
          <p-button v-if="keyType" @click="del">删除</p-button>
        </div>
      </div> -->
      <p-card
        style="width:100%"
        :tab-list="tabList"
        :active-tab-key="noTitleKey"
        @tabChange="key => onTabChange(key, 'noTitleKey')"
      >
        <div slot="tabBarExtraContent">
          <div class="btns1">
            <p-button type="primary" v-if="keyType" @click="handleOk">保存</p-button>
            <!-- <p-button type="primary" v-if="!keyType" @click="del">删除</p-button> -->
          </div>
        </div>
        <div v-show="noTitleKey === 'tab1'">
          <p-grid-form
            :ref="tablecolumns.modalItems.gridformref"
            :span="8"
            :label-col="{ span: 6 }"
            :items="tablecolumns.modalItems.items"
            @submit="hanlderSubmit"
          />
          <a-divider />
          <p-table
            bordered
            :autoLoad="false"
            dragle
            auto-width
            :remote-url="tablecolumns.modalItems.remoteUrl"
            :ref="tablecolumns.modalItems.ref"
            :row-key="tablecolumns.modalItems.rowkey"
            :columns="tablecolumns.modalItems.columns"
            :doneBefore="tablecolumns.modalItems.doneBefore"
            :selectedRowKeys.sync="ModalDataRowKeys"
            :row-selection="{ fixed: true, onChange: selectedRowsfun }"
            :data-source.sync="ModalData"
            :remoteParams="ModalItemsParams"
            :remoteBefore="tablecolumns.modalItems.remoteBefore"
            :rowSelectType="2"
            :scroll="{ x: 1500 }"
          >
            <template slot="number" slot-scope="text, record, index">
              <p-input-number
                style="width:80px;"
                @change="e => onChange(e, record, index)"
                :value="text"
                :min="1"
                :max="record.lossQty1"
              />
            </template>

            <template slot="opinion" slot-scope="text, record">
              <!-- {{ record }} -->
              <p-input style="width:80px;" v-model="record.opinion" />
            </template>
          </p-table>
          <!-- template -->
          <template v-if="businessData != 'int'">
            <a-divider />
            <p-grid-form
              :ref="tablecolumns.modalItems.ModalItemsOpinion.ref"
              :span="8"
              :label-col="{ span: 9 }"
              :items="tablecolumns.modalItems.ModalItemsOpinion.items"
              @submit="hanlderSubmit"
            />
          </template>
        </div>
        <div v-show="noTitleKey === 'tab2'">
          <main-table ref="maintable" :tablecolumns="tablecolumns"></main-table>
        </div>
      </p-card>
      <!-- </p-card> -->
    </p-spin>
  </div>
</template>

<script>
import { addItem, delItem } from '../api.js'
import MainTable from '../components/mainTable'
import tablecolumns from './config/tableconfjg'
import { setCargoOwner } from '@/views/kzyWMS/utils/setCargoOwner'
import pick from 'lodash.pick'
import { getBusiness } from '@/views/kzyWMS/api/business' // 系统参数接口

export default {
  data() {
    return {
      spinning: false,
      noTitleKey: 'tab1',
      key: 'tab1',
      tabList: [
        {
          key: 'tab1',
          tab: '操作'
        },
        {
          key: 'tab2',
          tab: '操作结果'
        }
      ],
      keyType: true,
      ModalItemsParams: { ...this.$store.state.user.warehouse },
      ModalData: [],
      selectedRow: [],
      ModalDataRowKeys: [],
      confirmLoading: false,
      visible: false,
      title: '不合格品报损申请',
      tablecolumns: tablecolumns(this),
      businessData: ''
    }
  },
  components: {
    MainTable
  },
  mixins: [setCargoOwner],
  mounted() {
    this.SetWarehouse()
  },
  created() {
    getBusiness().then(res => {
      this.businessData = res // 系统参数
      console.log(this.businessData)
    })
  },
  methods: {
    selectedRowsfun(selectedRowKeys, selectedRow) {
      this.selectedRow = selectedRow
      console.log(this.selectedRow)
    },
    //保存提取商品信息
    async save() {
      //   getCurrentRow
      let data = {}
      data.gspUnqualifiedLossDList = this.selectedRow
      //   console.log(this.selectedRow)
      if (this.businessData != 'int') {
        this.$refs[this.tablecolumns.modalItems.ModalItemsOpinion.ref].form.validateFields((err, value) => {
          if (!err) {
            console.log(value, '部门意见')
            data = { ...data, ...value }
          }
        })
      }

      this.$refs[this.tablecolumns.modalItems.gridformref].form.validateFields(async (err, value) => {
        if (!err) {
          console.log(value, '仓库货主id')
          data = { ...data, ...value }
          if (this.selectedRow.length > 0) {
            this.confirmLoading = true
            console.log(data)
            this.spinning = true
            try {
              let res = await addItem(data)
              this.spinning = false
              if (res.success) {
                this.confirmLoading = false
                this.visible = false
                this.$refs[this.tablecolumns.modalItems.ref].reload()
                if (this.businessData != 'int')
                  this.$refs[this.tablecolumns.modalItems.ModalItemsOpinion.ref].form.resetFields()
              } else {
                this.$exception(res)
              }
            } catch (error) {
              this.$exception(error)
              this.spinning = false
            }

            // let res = await addItem(data)
            // console.log(res)
            // this.spinning = false
            // if (res.success) {
            //   this.confirmLoading = false
            //   this.visible = false
            //   this.$refs[this.tablecolumns.modalItems.ref].reload()
            //   if (this.businessData != 'int')
            //     this.$refs[this.tablecolumns.modalItems.ModalItemsOpinion.ref].form.resetFields()
            //   //   this.$refs.maintable.Sub()
            // } else {
            //   this.confirmLoading = false
            //   this.$exception(res)
            // }
          } else {
            this.$message.info('请选择提取单')
          }
        }
      })
    },
    hanlderSubmit(event, form) {
      event.preventDefault()
      console.log('弹窗查询')
      form.validateFields((err, value) => {
        if (!err) {
          console.log(value, '=========')
          this.ModalItemsParams = { ...value }
          console.log(this.$refs[this.tablecolumns.modalItems.ref])
          //   this.$refs[this.tablecolumns.modalItems.ref].reload()
          //   console.log(this.$refs[this.tablecolumns.modalItems.ref])
        }
      })
    },
    showModal() {
      this.$refs.maintable.$refs[this.tablecolumns.gridform.ref].form.validateFields((err, value) => {
        if (!err) {
          //   console.log(value)
          this.visible = true
          //   console.log(this.$refs[this.tablecolumns.modalItems.ref])
          this.$nextTick(() => {
            this.$refs[this.tablecolumns.modalItems.gridformref].form.setFieldsValue(value)
            console.log(value)
            setTimeout(() => {
              this.ModalItemsParams = { ...value }
            }, 0)
            this.$refs[this.tablecolumns.modalItems.ModalItemsOpinion.ref].form.resetFields()
            this.selectedRow = []
          })
        } else {
          this.$message.warning('请选择货主和仓库名称')
        }
      })

      //   this.visible = true
    },
    handleOk(e) {
      let self = this
      this.$confirm({
        title: '确定要保存吗?',
        onOk() {
          self.save()
        }
      })
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
    },
    //删除
    del() {
      let that = this
      this.$confirm({
        title: '警告',
        content: `真的要删除选中行吗?`,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        async onOk() {
          let res = await delItem(that.$refs.maintable.MainTableselectedRowKeys)
          console.log(res)
          if (res.success) {
            that.$message.success('删除成功!')
            console.log(that.$refs.maintable.$refs[that.tablecolumns.MainTable.ref].reload())
            // that.$refs.maintable[that.tablecolumns.MainTable.ref].reload()
          } else {
            that.$exception(res)
          }
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    onChange(e, record, index) {
      this.ModalData[index].lossQty = e
      this.ModalData = [...this.ModalData]
    },
    SetWarehouse() {
      let warehouse = this.$store.state.user.warehouse
      console.log(this.$refs.modelFormType, '====')
      if (Object.keys(warehouse).length > 0) {
        if (this.$refs[this.tablecolumns.modalItems.gridformref]) {
          this.$refs[this.tablecolumns.modalItems.gridformref].form.setFieldsValue(
            pick(warehouse, 'warehouseId', 'warehouseCode', 'warehouseName')
          )
        }
        // modelFormType
      }
    },
    onTabChange(key, type) {
      console.log(key, type)
      this[type] = key
      key == 'tab1' && (this.keyType = true)
      key == 'tab2' && (this.keyType = false)
      if (key == 'tab2') {
        let data = this.$refs[this.tablecolumns.modalItems.gridformref].form.getFieldsValue()
        this.$refs.maintable.SetgridformValue(data)
      }
    }
  }
}
</script>

<style scoped>
.btns1 {
  width: 200px;
  margin-top: 10px;
  display: flex;
  justify-content: space-around;
}
</style>
