<template>
  <div>
    <p-card
      style="width:100%"
      :tab-list="tabList"
      :active-tab-key="noTitleKey"
      @tabChange="key => onTabChange(key, 'noTitleKey')"
    >
      <div slot="tabBarExtraContent">
        <!-- <p-button type="primary" v-if="!keyType" @click="del">删除</p-button> -->
        <a-space>
          <p-button type="primary" @click="recover">提取</p-button>
          <p-button type="primary" v-if="keyType" @click="save">保存</p-button>
        </a-space>
      </div>
      <!-- <p-card :title="title"> -->
      <!-- <div slot="extra">
        <div class="btns">
          <p-button @click="showModal">提取</p-button>
          <p-button @click="del">删除</p-button>
        </div>
      </div> -->
      <div v-show="noTitleKey === 'tab1'">
        <p-grid-form
          :ref="tablecolumns.modalItems.gridformref"
          :span="8"
          :label-col="{ span: 9 }"
          :items="tablecolumns.modalItems.items"
        />
        <a-divider />
        <p-table
          bordered
          :autoLoad="false"
          dragle
          auto-width
          :doneBefore="tablecolumns.modalItems.doneBefore"
          :remote-url="tablecolumns.modalItems.remoteUrl"
          :ref="tablecolumns.modalItems.ref"
          :row-key="tablecolumns.modalItems.rowkey"
          :columns="tablecolumns.modalItems.columns"
          @selectChange="selectChangeFun"
          :selectedRowKeys.sync="DataRowKeys"
          :data-source.sync="DataList"
          :remoteParams="ModalItemsParams"
          :rowSelectType="2"
          :scroll="{ x: 1500 }"
        >
          <!-- :remoteBefore="tablecolumns.modalItems.remoteBefore" -->
          <template slot="lossQty" slot-scope="text, record, index">
            <p-input-number
              style="width:80px;"
              @change="e => onChangelossQty(e, record, index)"
              :value="text"
              :min="1"
              :max="parseInt(record.lossQty1)"
            />
          </template>

          <template slot="destroyedQty" slot-scope="text, record, index">
            <p-input-number
              style="width:80px;"
              @change="e => onChangedestroyedQty(e, record, index)"
              :value="text || 0"
              :min="0"
              :max="parseInt(record.lossQty1)"
            />
          </template>

          <template slot="destroyQty" slot-scope="text, record, index">
            <p-input-number
              style="width:80px;"
              @change="e => onChangedestroyQty(e, record, index)"
              :value="text"
              :min="0"
              :max="parseInt(record.lossQty1)"
            />
          </template>
        </p-table>
        <!-- <a-divider />
        <p-grid-form
          :ref="tablecolumns.modalItems.ModalItemsOpinion.ref"
          :span="8"
          :label-col="{ span: 9 }"
          :items="tablecolumns.modalItems.ModalItemsOpinion.items"
        /> -->
      </div>
      <div v-show="noTitleKey === 'tab2'">
        <main-table ref="maintable" :tablecolumns="tablecolumns"></main-table>
        <!-- </p-card> -->
      </div>
    </p-card>
    <p-modal
      ref="model"
      width="80%"
      :maskClosable="false"
      :enlargeable="true"
      :draggable="true"
      title="提取单据"
      :visible="visible"
      :okText="'确认'"
      :confirm-loading="confirmLoading"
      @ok="submit"
      @cancel="handleCancel"
    >
      <!-- <div style="width:100%;height:20px;">
        <p-button style="float:right;margin-right:10px;" @click="save">确认</p-button>
      </div> -->
      <p-grid-form
        ref="recoverForm"
        :span="8"
        :label-col="{ span: 9 }"
        :items="tablecolumns.recover.items"
        @submit="hanlderSubmit"
      />
      <a-divider />
      <p-table
        bordered
        dragle
        auto-width
        :remote-url="tablecolumns.recover.remoteUrl"
        ref="ModelTable"
        :row-key="tablecolumns.recover.rowkey"
        :columns="tablecolumns.recover.columns"
        :autoLoad="false"
        @selectChange="selectChange"
        :selectedRowKeys.sync="ModalDataRowKeys"
        :data-source.sync="ModalData"
        :remoteParams="recoverParams"
        :remoteBefore="tablecolumns.recover.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" />
        </template> -->
      </p-table>
    </p-modal>
  </div>
</template>

<script>
import { DestroyAdd, DestroydelIds } from '../api.js'
import MainTable from '../components/mainTable'
import tablecolumns from './config/tableconfjg'
import pick from 'lodash.pick'
import { setCargoOwner } from '@/views/kzyWMS/utils/setCargoOwner'
import { getBusiness } from '@/views/kzyWMS/api/business' // 系统参数接口
export default {
  data() {
    return {
      noTitleKey: 'tab1',
      key: 'tab1',
      tabList: [
        {key: 'tab1', tab: '操作'},
        {key: 'tab2', tab: '操作结果'}
      ],
      keyType: true,
      ModalItemsParams: { ...this.$store.state.user.warehouse, status: '10', cargoOwnerId: '' },
      recoverParams: {},
      ModalData: [],
      DataList: [],
      selectedRow: [],
      DataRowKeys: [],
      ModelselectedRows: [], //弹窗表格选择信息
      ModalDataRowKeys: [],
      confirmLoading: false,
      visible: false,
      title: '不合格品销毁申请',
      tablecolumns: tablecolumns(this),
      businessData: ''
    }
  },
  mixins: [setCargoOwner],
  components: {
    MainTable
  },
  created() {
    getBusiness().then(res => {
      this.businessData = res // 系统参数

      //   console.log(this.businessData, this.tablecolumns)
    })
  },
  mounted() {
    this.SetWarehouse()
  },
  methods: {
    //弹窗点击确认
    submit() {
      if (this.ModelselectedRows.length == 0) {
        this.$message.info('请选择提取单')
        return
      }
      this.DataList = this.ModelselectedRows
      console.log(this.ModelselectedRows, this.DataList)
      this.visible = false
    },
    //弹窗选择数据
    selectChange(selectedRowKeys, selectedRows) {
      console.log(selectedRows)
      this.ModelselectedRows = selectedRows
    },
    selectChangeFun(selectedRowKeys, selectedRows) {
      this.selectedRow = selectedRows
    },
    //点击提取按钮
    recover() {
      this.$refs[this.tablecolumns.modalItems.gridformref].form.validateFields((err, value) => {
        if (!err) {
          console.log(value)
          this.visible = true
          this.ModalData = []
          this.ModalDataRowKeys = []
          this.$nextTick(() => {
            this.$refs.recoverForm.form.setFieldsValue(value)
          })
          //   data = { ...data, ...value }
        }
      })
    },

    async save() {
      //保存提取商品信息
      //   getCurrentRow
      if (this.selectedRow.length == 0) {
        return
      }
      let data = {}
      let keys = ['cargoOwnerId', 'cargoOwnerName', 'dcId', 'enterpriseId', 'warehouseId', 'warehouseName', 'source']
      keys.forEach(item => {
        data[item] = this.selectedRow[0][item] || null
      })
      console.log(data)
      data.gspUnqualifiedDestroyDList = this.selectedRow
      data.gspUnqualifiedDestroyDList.forEach(item => {
        //   item
        console.log(item.lossQty, item.destroyQty)
        // item.destroyQty = item.lossQty
      })
      try {
        let res = await DestroyAdd(data)
        if (res.success) {
          this.$message.success(res.message)
          this.DataList = []
          this.DataRowKeys = []
          // this.remoteParams = { ...this.remoteParams };
        } else {
          this.$exception(res)
        }
      } catch (error) {
        this.$exception(error)
      }
    },
    hanlderSubmit(event, form) {
      event.preventDefault()
      console.log('弹窗查询')
      form.validateFields((err, value) => {
        if (!err) {
          console.log(value, '=========')
          this.recoverParams = { ...this.recoverParams, ...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, refBillId: '111', itemId: '111' }
            }, 0)
            this.$refs[this.tablecolumns.modalItems.ModalItemsOpinion.ref].form.resetFields()
            this.selectedRow = []
          })
        } else {
          this.$message.warning('请选择货主和仓库名称')
        }
      })

      //   this.visible = true
    },
    handleOk(e) {
      this.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 DestroydelIds(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')
        }
      })
    },
    onChangelossQty(e, record, index) {
      console.log(this.ModalData[index])
      this.ModalData[index].lossQty = e
    },
    onChangedestroyedQty(e, record, index) {
      console.log(this.ModalData[index])
      this.ModalData[index].destroyedQty = e
    },
    onChangedestroyQty(e, record, index) {
      console.log(this.ModalData[index], e)
      this.ModalData[index].destroyQty = e
      console.log(this.ModalData[index].destroyQty)
    },
    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>
.btns {
  width: 200px;
  margin-top: 10px;
  display: flex;
  justify-content: space-around;
}
</style>
