<!-- 订单优先级-->
<template>
  <div>
    <p-modal title='修改提货方式' :visible='visible' :enlargeable='true' :draggable='true'
             @ok='handleOk'
             @cancel='handleCancel'
             @enlargeChange='enlargeChange'>
      提货方式：
      <p-select default-value=''
                style='width: 200px'
                :remoteUrl="{
               url: upcloud_base_common + `/dict/listbytype?dicttypeCodes=pub_workstage_delivertype`,
          method: 'post',
        }"
                :replaceFields="{
          label: 'dictName',
          value: 'dictCode',
        }"
                :autoLoad='true'
                :destroyOptions='true'
                :remoteBefore='remoteBefore'
                @change='handleChange'
      />
    </p-modal>

    <p-card title='订单优先级'>
      <template slot='extra'>
        <p-button icon='eye' @click='isShow = !isShow' style='margin-right: 15px'>{{ isShow ? '隐藏' : '显示' }}
        </p-button>
        <p-button type='primary' icon='check' @click='finishOk'>提升优先级</p-button>
      </template>
      <p-grid-form v-show='isShow' ref='search' :items='items' @submit='handlerSubmit' />
      <p-table
        ref='tableOrderPriority'
        :columns='columns'
        :data-source='data'
        rowKey='id'
        dragle
        auto-width
        :scroll='{ x: true }'
        hasRowSelectCheck
        rowSelectFixed
        :remoteUrl='remoteUrl'
        :remoteData='remoteUrl.params'
        @checkRow='checkRow'
        :pagination='10'
        :loading='loading'
        bordered
      >
        <template slot='receiveWay' slot-scope='text, rows, index'>
          {{ text }}
          <!-- <a style="float: right" v-show="rows.status == '已经创建'" @click="edit(rows.id)">修改</a> -->
        </template>
        <template slot='type' slot-scope='text, rows, index'>
          {{ do_bill_typeOption(text) }}
        </template>
        <template slot='attainDate' slot-scope='text, rows, index'>
          {{ text ? moment(text).format('YYYY-MM-DD HH:mm') : '' }}
        </template>
      </p-table>
    </p-card>
  </div>
</template>

<script>
// 设置默认仓库
import { setwarehouse } from '@/views/kzyWMS/SearchModal/mixins_warehouse.js'
import { items, columns } from './config'
import { bill_query, bill_update, dict_listbytype, cancelBill } from './api'
import { sorter } from '@/views/kzyWMS/utils/sort.js'
import { upcloud_base_common, upcloud_base_wh_outbound } from '@/config/serviceSettings'

export default {
  mixins: [setwarehouse],
  data() {
    return {
      upcloud_base_common,
      items,
      columns: sorter(columns),
      data: [],
      loading: false,
      selectedRows: [],
      option: [], //提货方式
      do_bill_type: [], //来源单类型
      visible: false,
      isShow: true,
      rows: {
        id: '',
        receiveWayId: '' //提货方式id
      },
      remoteUrl: {
        url: upcloud_base_wh_outbound + '/bill/query',
        method: 'post',
        headers: {
          'Content-Type': 'application/JSON'
        },
        params: {}
      },
      pagination: {
        total: 0,
        pageSize: 10, //每页中显示10条数据
        current: 1,
        showSizeChanger: true,
        pageSizeOptions: ['10', '15', '20'], //每页中显示的数据
        showTotal: (total) => `共有 ${total} 条数据` //分页中显示总的数据
      },
      ones_max_num: []
    }
  },
  created() {
    this.remoteUrl.params.status = 'CREATED'
    this.remoteUrl.params.warehouseId = this.$store.getters.warehouse.warehouseId
    this.remoteUrl.params.warehouseName = this.$store.getters.warehouse.warehouseName
    dict_listbytype({ dicttypeCodes: 'pub_workstage_delivertype' }).then((res) => {
      if (res.success) {
        this.option = res.data
        console.log('提货方式：', this.option)
      }
    })
    dict_listbytype({ dicttypeCodes: 'do_bill_type' }).then((res) => {
      if (res.success) {
        this.do_bill_type = res.data
        console.log('出库单类型(来源单类型)：', this.do_bill_type)
      }
    })

    dict_listbytype({ dicttypeCodes: 'WAVE_BILL_MAX_NUM' }).then((res) => {
      if (res.success) {
        this.ones_max_num = res.data[0].dictName
        console.log('单次提升优先级最大单量：', this.ones_max_num)
      }
    })
  },
  mounted() {
    // this.getData({...this.$refs.search.form.getFieldsValue()});
    // this.$refs.search.form.setFieldsValue({status:'CREATED'})
    let warehouseName = this.$store.getters.warehouse.warehouseName
    let warehouseId = this.$store.getters.warehouse.warehouseId
    this.$refs.search.form.setFieldsValue({
      warehouseName: warehouseName,
      warehouseId: warehouseId
    })
  },
  methods: {
    getData(params) {
      params = {
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...params
      }
      this.loading = true
      bill_query(params).then((res) => {
        if (res.success) {
          if (res.data) {
            // 降序
            this.data = [...res.data.list.sort((a, b) => b.priority - a.priority)]
            this.data = this.data.filter((item) => item.status != 'PICKED')
            this.pagination.total = Number(this.data.length)
          } else {
            this.data.length = 0
          }
        } else {
          this.$exception(res)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 弹出编辑提货方式
    edit(id) {
      this.visible = true
      this.rows.id = id
    },
    cancelFun(id) {
      let values = this.$refs.search.form.getFieldsValue()
      let params = {
        warehouseId: values.warehouseId,
        billGroupId: id
      }
      cancelBill(params).then((res) => {
        if (res.success) {
          this.$message.success('操作成功！')
          this.getData({ ...this.$refs.search.form.getFieldsValue() })
        } else {
          this.$exception(res)
        }
      })
    },
    // 改变提货方式时
    handleChange(value) {
      console.log(`selected ${value}`)
      this.rows.receiveWayId = value
    },
    // 弹出窗确认
    handleOk(e) {
      if (this.rows.receiveWayId) {
        bill_update([{ id: this.rows.id, receiveWay: this.rows.receiveWayId }]).then((res) => {
          if (res.success) {
            this.$message.success('修改成功！')
            this.visible = false
            this.getData({ ...this.$refs.search.form.getFieldsValue() })
          } else {
            this.$exception(res)
          }
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.$message.warning('请选择提货方式！')
      }
    },
    handleCancel(e) {
      console.log('Clicked cancel button')
      this.visible = false
    },
    enlargeChange(isEnlarge) {
      console.log(isEnlarge)
    },
    handlerSubmit(event, form) {
      event.preventDefault()
      // console.log("getFieldsValue:",form.getFieldsValue());
      // this.getData(form.getFieldsValue())
      this.$refs.search.form.validateFields((err, values) => {
        if (!err) {
          console.log('验证通过: ', values)
          // this.getData(values);
          this.remoteUrl.params = { ...values }
        }
      })
    },
    remoteBefore(vn, p) {
      p.data = {
        // pageNum:p.data.pageNum,
        // pageSize:p.data.pageSize,
        ...this.$refs.search.form.getFieldsValue()
      }
      return p
    },
    remoteBefore2(vn, p) {
      console.log(this.$refs.search.form.getFieldsValue())
      let data = this.$refs.search.form.getFieldsValue()
      p.data = { pageNum: p.data.pageNum, pageSize: p.data.pageSize, ...data }
      return p
    },
    // 重置
    hanlderRest(event, form) {
      this.$refs.search.form.resetFields()
    },
    // 补货完成
    checkRow(selectedRowKeys, selectedRows) {
      console.log('操作选中行的checkbox：', selectedRowKeys, selectedRows)
      this.selectedRows = [...selectedRows]
    },
    finishOk() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择数据！')
        return
      }
      // 增加校验勾选的订单数量，是否超过业务参数设置【单次提升优先级最大单量】，若已超过，则拦截提示：单次最多提升XXXX个订单的优先级！
      if (this.selectedRows.length > this.ones_max_num.length) {
        this.$message.warning(`单次最多提升[${this.ones_max_num.length}]个订单的优先级！`)
        return
      }
      const params = this.selectedRows.map((item) => {
        const { id, totalQty, warehouseId } = item
        return {
          id, totalQty, warehouseId,
          priority: 9999
        }
      })
      this.loading = true
      bill_update(params).then((res) => {
        if (res.success) {
          this.$message.success('提升优先级成功！')
          this.getData({ ...this.$refs.search.form.getFieldsValue() })
        } else {
          this.$exception(res)
        }
      }).finally(() => {
        this.loading = false
      })
    },
    changePagination(pagination, filters, sorter) {
      // 分页变化
      console.log(pagination, filters, sorter, '分页变化分页变化')
      this.pagination = pagination
      this.getData({ ...this.$refs.search.form.getFieldsValue() }) //分页查询所有列表
    },
    // 过滤提货方式数据字典
    receiveWay(text) {
      let temp = this.option.find((v) => v.dictId == text)
      return temp ? temp.dictName : ''
    },
    // 出库单类型(来源单类型)：
    do_bill_typeOption(text) {
      let temp = this.do_bill_type.find((v) => v.dictId == text)
      return temp ? temp.dictName : ''
    }
  } // methods
}
</script>

<style scoped lang='less'>
::v-deep {
  .ant-table-row-selected {
    background: red;
  }

  .p-table tr.active > td {
    background: none !important;
  }
}
</style>
