<template>
  <div>
    <!-- :title="title" -->
    <!-- :tab-list="titleList" :active-tab-key="title" -->
    <p-card :title="title">
      <div slot="extra">
        <div class="btns">
          <p-button v-if="chektype" type="primary" @click="check(true)">审核</p-button>
          <p-button type="primary"  @click="check(false)">驳回</p-button>
          <!-- v-if="regValue" -->
          <p-button type="primary" @click="print">打印</p-button>
        </div>
      </div>
      <p-spin size="small" :spinning="spinning">
        <main-table
          ref="maintable"
          :tablecolumns="tablecolumns"
          @SetRegvalue="SetRegvalue"
          @changecolumns="changecolumns"
          @splitOMS="splitOMS"
        >
        </main-table>
      </p-spin>
    </p-card>
    <p-modal
      width="80%"
      :maskClosable="false"
      :enlargeable="true"
      :draggable="true"
      :title="tablecolumns.modalItems.title"
      :visible="visible"
      :okText="'保存'"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @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="tablecolumns.modalItems.gridformref"
        :span="8"
        :label-col="{ span: 9 }"
        :items="tablecolumns.modalItems.items"
        @submit="hanlderSubmit"
      />
      <a-divider />
      <p-table
        bordered
        dragle
        auto-width
        :remote-url="tablecolumns.modalItems.remoteUrl"
        :ref="tablecolumns.modalItems.ref"
        :row-key="tablecolumns.modalItems.rowkey"
        :columns="tablecolumns.modalItems.columns"
        :autoLoad="false"
        :selectedRowKeys.sync="ModalDataRowKeys"
        :data-source.sync="ModalData"
        :row-selection="{ fixed: true, onChange: selectedRowsfun }"
        :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" />
        </template>
      </p-table>
      <a-divider />
      <p-grid-form
        :ref="tablecolumns.modalItems.ModalItemsOpinion.ref"
        :span="8"
        :label-col="{ span: 9 }"
        :items="tablecolumns.modalItems.ModalItemsOpinion.items"
        @submit="hanlderSubmit"
      />
    </p-modal>

    <p-modal
      :title="'拆分总数量' + totalNum"
      :visible="visible_split"
      destroyOnClose
      :draggable="true"
      :enlargeable="true"
      width="80%"
      :footer="null"
      @cancel="handleCancel"
    >
      <!-- 拆分弹窗 -->

      <div style="text-align: right; margin-bottom: 20px">
        <p-button type="primary" icon="bars" @click="addRow" style="margin-right: 15px">新增拆分</p-button>
        <p-button type="primary" icon="delete" @click="delShow" style="margin-right: 15px">删除拆分</p-button>
        <p-button type="primary" icon="check" @click="splithandleOk" style="margin-right: 15px">确定拆分</p-button>
      </div>
      <p-table-edit-pro
        ref="table2"
        editor-row-table
        :columns="tablecolumns.SubTable.OMScolumns.slice(0, -1)"
        :data-source.sync="spltData"
        rowKey="key"
        dragle
        @checkRow="checkRow"
        :row-select-type="1"
        bordered
        :scroll="{ x: 1500 }"
      >
      </p-table-edit-pro>
    </p-modal>
  </div>
</template>

<script>
import { batchAuditYes, batchAuditNo } from '../api.js'
import MainTable from './mainTable'
import { toPrintServer, tempType } from '@/views/kzyWMS/utils/printServer.js'
import tablecolumns from './config/tableconfjg'
// import { setwarehouse } from '../mixin/warehousemixin.js'
import { getBusiness } from '@/views/kzyWMS/api/business' // 系统参数接口
export default {
  data() {
    return {
      splitIndex: null,
      spltData: [],
      splitData: [],
      selectedRowKeys: [],
      totalNum: 1,
      chektype: true,
      spinning: false,
      MainTableselectedRowKeys: [],
      ModalItemsParams: {},
      ModalData: [],
      selectedRow: [],
      ModalDataRowKeys: [],
      confirmLoading: false,
      visible: false,
      visible_split: false,
      regValue: true,
      title: '不合格品报损审核',
      tablecolumns: tablecolumns(this)
    }
  },
  computed: {
    titleList() {
      let that = this
      return [
        {
          tab: that.title,
          key: that.title
        }
      ]
    }
  },
  components: {
    MainTable
  },
  //   mixins: [setwarehouse],打他
  methods: {
    //拆分数据添加到明细表
    splitDataPush(list) {
      console.log(this.splitIndex)
      this.$refs.maintable.pushsubList(list, this.splitIndex)
    },
    splithandleOk() {
      let t = this.spltData.some(item => item.lossQty == 0)
      if (t) {
        this.$message.warning('拆分数量不能等于0')
        return
      }
      //
      let num = 0
      this.spltData.forEach(item => {
        num = num + parseInt(item.lossQty)
      })
      console.log(num)
      if (num != this.totalNum) {
        this.$message.warning('拆分数量总和与之前数量不等,请修改!')
        return
      }
      this.spltData.forEach(item => (item.id = item.id + item.key)) //保证id不重复保存
      this.splitDataPush(this.spltData)
      this.spltData = []
      this.visible_split = false
    },
    addRow() {
      this.spltData.push({
        ...this.splitData,
        lossQty: 0,
        key: 'key' + parseInt(Math.random() * 10000)
      })
      console.log('data2', this.data2)
    },
    delShow() {
      let _this = this
      if (this.selectedRowKeys.length) {
        this.$confirm({
          title: '删除',
          content: '您确定要删除吗?',
          onOk() {
            _this.$refs.table2.removeRow(_this.selectedRowKeys)
            _this.selectedRowKeys.length = 0
          },
          onCancel() {}
        })
      } else {
        this.$message.warning('请选择数据！')
      }
    },
    checkRow(selectedRowKeys, selectedRows) {
      console.log('selectedRowKeys, selectedRows', selectedRowKeys, selectedRows)
      this.selectedRowKeys = [...selectedRowKeys]
    },
    //拆分OMS 明细单
    splitOMS(value) {
      console.log(value)
      this.splitIndex = value.index
      this.totalNum = value.record.lossQty
      console.log(this.totalNum)
      console.log(this.totalNum < 1)
      if (this.totalNum < 2) {
        this.$message.warning('数量小于1不能进行拆分!')
        return
      }
      this.visible_split = true
      this.splitData = value.record
      this.spltData = [{ ...value.record, key: 'key' + parseInt(Math.random() * 10000) }]
    },
    //OMS单据修改明细表配置
    changecolumns(value) {
      console.log(value)
      if (value?.source == 'OMS') {
        this.tablecolumns.SubTable.columns = this.tablecolumns.SubTable.OMScolumns
      } else if (value?.source == 'WMS') {
        this.tablecolumns.SubTable.columns = this.tablecolumns.SubTable.WMScolumns
      }
    },
    async SetRegvalue(bool) {
      let res = await getBusiness()
      console.log(res)
      //   console.log(bool)
      if (res != 'int') this.regValue = bool
    },

    async check(type) {
      let that = this
      if (!this.spinning) {
        console.log('审核')
        //   console.log(this.$refs.maintable.MainTableselectedRowKeys)
        //   console.log(this.$refs.maintable.data)
        let a = this.$refs.maintable.data.filter(item => {
          return this.$refs.maintable.MainTableselectedRowKeys.some(item1 => {
            return item.id == item1
          })
        })
        console.log(a, '====') //主表信息
        // if (a.length > 0) {

        if (a.length == 0) {
          this.$message.info('请选择数据')
          return
        }
        // a.forEach(item => {
        //   if (item.source == 'OMS') {
        //     if (a.length != 1) {
        //       this.$message.info('OMS请选择一条数据进行审核')
        //       return
        //     } else {
        //       console.log(item)
        //     }
        //   }
        // })
        let keys = a.some(item => item.source == 'OMS')
        if (keys && a.length == 1) {
          console.log('OMS 一条数据')
          this.$refs.maintable.$refs[this.tablecolumns.gridform.ref].form.validateFields(async (err, value) => {
            if (!err) {
              console.log(value)
              let b = a.map(item => {
                return (item = { ...item, ...value })
              })
              b[0].gspUnqualifiedLossDList = that.$refs.maintable.GetSubTabledata()
              if (type) {
                this.spinning = true
                let res = await batchAuditYes(b)
                if (res.success) {
                  that.$message.success('审核成功!')
                  that.$refs.maintable.$refs[that.tablecolumns.MainTable.ref].reload()
                  that.$refs.maintable.clear()
                } else {
                  that.$exception(res)
                }
                this.spinning = false
              } else {
                console.log('驳回')
                this.spinning = true
                let res = await batchAuditNo(b)
                if (res.success) {
                  that.$message.success('驳回成功!')
                  that.$refs.maintable.$refs[that.tablecolumns.MainTable.ref].reload()
                  that.$refs.maintable.clear()
                } else {
                  that.$exception(res)
                }
              }
              this.spinning = false
            } else {
              this.$message.info('请选择数据')
            }
          })
        } else if (keys && a.length > 1) {
          this.$message.info('OMS请选择一条数据进行审核')
          return
        }
        if (!keys) {
          //全为WMS订单 走正常审核
          this.$refs.maintable.$refs[this.tablecolumns.gridform.ref].form.validateFields(async (err, value) => {
            if (!err) {
              console.log(value)
              let b = a.map(item => {
                return (item = { ...item, ...value })
              })
              if (type) {
                this.spinning = true
                let res = await batchAuditYes(b)
                if (res.success) {
                  that.$message.success('审核成功!')
                  that.$refs.maintable.$refs[that.tablecolumns.MainTable.ref].reload()
                  that.$refs.maintable.clear()
                } else {
                  that.$exception(res)
                }
                this.spinning = false
              } else {
                console.log('驳回')
                this.spinning = true
                let res = await batchAuditNo(b)
                if (res.success) {
                  that.$message.success('驳回成功!')
                  that.$refs.maintable.$refs[that.tablecolumns.MainTable.ref].reload()
                  that.$refs.maintable.clear()
                } else {
                  that.$exception(res)
                }
              }
              this.spinning = false
            } else {
              this.$message.info('请选择数据')
            }
          })
        }
      }

      // auditText:"[string] 审核意见"  status:"[string] 状态：10=初始 20=已审批 30=已驳回"  id:"[string] undefined"
      //   let res = await batchAuditYes(this.$refs.maintable.MainTableselectedRowKeys)
      //   if (res.success) {
      //     that.$message.success('审核成功!')
      //     console.log(that.$refs.maintable.$refs[that.tablecolumns.MainTable.ref].reload())
      //   } else {
      //     that.$exception(res)
      //   }
    },
    async print() {
      console.log('打印')
      let list = this.$refs.maintable.GetselectedRow()
      let sublist = this.$refs.maintable.GetSubTabledata()
      console.log(list)
      if (list.length == 1) {
        console.log('主表数据', list)
        console.log('子表数据', sublist)
        if (sublist.length == 0) {
          this.$message.warning('请先查询明细表数据!')
          return
        }

        let warehouse = this.$store.state.user.warehouse
        const warehouseId = warehouse.warehouseId
        console.log(list[0])
        const printParms = {
          planId: list[0].id
        }
        let printdata = {
          head: list[0],
          table: sublist
        }
        console.log(printdata, printParms)
        let res = await toPrintServer(printdata, warehouseId, tempType.GSP_BS, printParms)
        console.log(res)
        if (!res.success) {
          this.$exception(res)
          return
        }
      } else {
        this.$message.warning('打印时请选择一条数据!')
      }
    },
    selectedRowsfun(selectedRowKeys, selectedRow) {
      console.log(selectedRowKeys, selectedRow)
      this.ModalDataRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    // async save() {
    //   //保存提取商品信息
    //   //   getCurrentRow
    //   let data = {}
    //   data.gspUnqualifiedLossDList = this.selectedRow
    //   //   console.log(this.selectedRow)
    //   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((err, value) => {
    //     if (!err) {
    //       //   console.log(value, '仓库货主id')
    //       data = { ...data, ...value }
    //     }
    //   })
    //   if (this.selectedRow.length > 0) {
    //     console.log(data)
    //     let res = await addItem(data)
    //     console.log(res)
    //     if (res.success) {
    //       this.confirmLoading = false
    //       this.visible = false
    //       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) {
      this.confirmLoading = true
      this.save()
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
      this.visible_split = 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) {
      //   console.log(e, record, value)
      //   e = record.number
      //   e = value
      console.log(this.ModalData[index])
      this.ModalData[index].lossQty = e
    }
  }
}
</script>

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