<template>
  <div>
    <p-card title="出库单打印">
      <span slot="extra">
        <template>
          <p-checkbox-group v-model="checkedList" :options="plainOptions" @change="onChange" />
          <p-button type="primary" style="margin-left: 20px; margin-right: 10px" @click="clickBtn()">打印</p-button>
        </template>
      </span>
      <div class="gridClass">
        <p-grid-form
          :span="6"
          ref="forms"
          :labelCol="{ span: 8 }"
          :wrapperCol="{ span: 16 }"
          :items="itemDatas"
          @submit="hanlderSubmit"
        ></p-grid-form>
      </div>
      <p-table
        ref="table"
        :scroll="{ x: true }"
        row-key="billid"
        :bordered="true"
        dragle
        auto-width
        :autoLoad="false"
        :columns="tableColumns"
        :selectedRowKeys.sync="selectedRowKeys"
        :remoteUrl="tableRemoteUrl"
        :remoteBefore="remoteBefore"
        :remoteParams="remoteParams"
        @selectChange="selectChange"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="checkDetail(record)" style="margin-right: 10px" href="javascript:;">查看详情</a>
        </span>
      </p-table>
    </p-card>
    <detail-page ref="detail" :rowData="rowData" />
  </div>
</template>

<script>
import { genWarehouseAuthSearchModal, genCargoownerAuthSearchModal } from '@/views/kzyWMS/SearchModal'
import API from '@/views/kzyWMS/bound/api/default'
import { remote } from './config/remote'
import { SERVICE_DATA_API_BASE } from '@/config/serviceSettings'
import detailPage from './components/detail'
import { getCargoOwner } from '../../../utils/index'
import { queryOutboundPrintList } from '../../api/api'
import { toPrintServer } from '@/views/kzyWMS/utils/printServer.js'

const items = function (that) {
  let grid = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
    span: 6,
  }
  return [
    ...genWarehouseAuthSearchModal(1, true, false, null, null, grid),
    ...genCargoownerAuthSearchModal(1, true, false, null, null, grid),
    {
      type: 'select',
      name: 'consignorType',
      label: '货主类型',
      value: '',
      autoLoad: true,
      ...remote('cargoowner_type'),
    },
    {
      type: 'select',
      name: 'billType',
      label: '订单类型',
      value: '',
      autoLoad: true,
      ...remote('	billtype'),
    },
    {
      type: 'row',
      label: '开票日期',
      name: 'ff',
      list: [
        {
          type: 'date',
          name: 'billDateStart',
          style: { paddingRight: '5px' },
          format: 'YYYY-MM-DD',
          placeholder: '请输入开始日期',
          value: '',
        },
        {
          style: { paddingLeft: '5px' },
          type: 'date',
          name: 'billDateEnd',
          placeholder: '请输入结束日期',
          format: 'YYYY-MM-DD',
          value: '',
        },
      ],
    },
    {
      type: 'select',
      name: 'printFlag',
      label: '打印状态',
      value: '',
      options: [
        { label: '未打印', value: '0' },
        { label: '打印', value: '1' },
      ],
    },
    {
      type: 'input',
      name: 'unitMnemonicCode',
      label: '单位助记码',
    },
    {
      type: 'input',
      name: 'billNo',
      label: '单据编号',
    },
    {
      type: 'select',
      // mode: 'multiple',
      name: 'lineCode',
      label: '配送方向',
      autoLoad: true,
      ...remote('common_shiplineid'),
    },
    {
      span: 6,
      type: 'buttonGroup',
      style: { textAlign: 'left' },
      options: [
        {
          value: '查询',
          icon: 'search',
          btnType: 'primary',
          style: 'margin-left:30px;margin-right:10px;',
          htmlType: 'submit',
          on: {
            click: (event, form) => {
              form.validateFields((error, values) => {
                if (!error) {
                  // values.deliveries = [values.deliveries]
                  that.remoteParams = values
                }
              })
            },
          },
        },
        {
          value: '重置',
          name: 'ccz',
          icon: 'redo',
          on: {
            click(event, form) {
              form.resetFields()
            },
          },
        },
      ],
    },
  ]
}
const columns = [
  { dataIndex: 'consignorcode', title: '货主编号', key: 'consignorcode', width: 150 },
  { dataIndex: 'consignorname', title: '货主名称', key: 'consignorname', width: 180 },
  // { dataIndex: 'billno', title: '单据编号', key: 'billno', width: 100 },
  { dataIndex: 'remark', title: '客户备注', key: 'remark', width: 100 },
  { dataIndex: 'lineName', title: '配送方向', key: 'lineName', width: 80 },
  { dataIndex: 'isAccompanyInvoice', title: '是否随货同行', key: 'isAccompanyInvoice', width: 100 },
  { dataIndex: 'drugTestNum', title: '药检报告数', key: 'drugTestNum', width: 100 },
  { dataIndex: 'coldChainNum', title: '冷链数', key: 'coldChainNum', width: 120 },
  { dataIndex: 'grshFlag', title: '个人清单数', key: 'grshFlag', width: 100 },
  { dataIndex: 'contractList', title: '合同数', key: 'contractList', width: 100 },
  { dataIndex: 'billDate', title: '单据日期', key: 'billDate', width: 100 },
  { dataIndex: 'shippercode', title: '单位编号', key: 'shippercode', width: 100 },
  { dataIndex: 'shippername', title: '单位名称', key: 'shippername', width: 100 },
  { dataIndex: 'printCount', title: '打印状态', key: 'printCount', width: 80 },
  { dataIndex: 'stageCodeMin', title: '暂存区启始号', key: 'stageCodeMin', width: 120 },
  { dataIndex: 'stageCodeMax', title: '暂存区终止号', key: 'stageCodeMax', width: 150 },
  { dataIndex: 'arrivalMode', title: '提货方式', key: 'arrivalMode', width: 150 },
  {
    dataIndex: 'action',
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 80,
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  name: 'outBoundPrint',
  data() {
    return {
      remoteParams: {},
      plainOptions: ['随货通行联', '冷链', '合同', '个人清单', '药检单', '两票制', '电子发票'],
      checkedList: ['随货通行联', '冷链', '合同', '个人清单', '药检单', '两票制', '电子发票'],
      checkedObj: {
        随货通行联: 'CommonShippingSlip',
        冷链: 'ColdChain',
        合同: 'Contract',
        个人清单: 'PersonalList',
        药检单: 'MedicineCheckReport',
        两票制: 'TwoVoteSystem',
        电子发票: 'ElectronicInvoice',
      },
      selectedRowKeys: [],
      itemDatas: items(this),
      rowData: {},
      tableColumns: columns,
      tableRemoteUrl: {
        url: SERVICE_DATA_API_BASE + '/search/page',
        method: 'post',
        headers: {
          'Content-Type': 'application/JSON',
        },
        params: {
          id: 'listOutBoundListToPrint',
        },
      },
    }
  },
  components: {
    detailPage,
  },
  created() {
    this.getAuthBycargoOwner()
  },
  mounted() {
    let user = this.$store.state.user
    let warehouse = this.$store.state.user.warehouse
    this.$refs.forms.form.setFieldsValue({
      warehouseName: warehouse.warehouseName,
      warehouseId: warehouse.warehouseId,
    })
  },
  methods: {
    async getAuthBycargoOwner() {
      await getCargoOwner().then((res) => {
        if (res.success) {
          this.$nextTick(() => {
            this.$refs.forms.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
        }
      })
    },
    onChange(checkedList) {
      this.checkedList = checkedList
    },
    clickBtn(item) {
      // 按钮
      if (this.selectedRowKeys.length < 1) return this.$message.warn('请选择单据！')
      if (this.checkedList.length < 1) return this.$message.warn('请选择打印文件类型！')
      let printTypes = []
      this.checkedList.map((idx) => {
        if (Object.keys(this.checkedObj).includes(idx)) {
          printTypes.push(this.checkedObj[idx])
        }
      })
      let params = {
        billIds: this.selectedRowKeys,
        printTypes: printTypes,
      }
      queryOutboundPrintList(params).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        console.log(res, '55555555555555')
        const printData = res.data ? res.data : []
        printData.map((itemList) => {
          if (itemList.data && itemList.data.length > 0) {
            toPrintServer(itemList.data, this.$store.getters.warehouse.warehouseId, itemList.dataMark).then((res) => {
              if (!res.success) {
                this.$exception(res)
                return
              }
              this.$message.success(res.message)
            })
          }
        })
      })
    },
    hanlderSubmit(event, form) {
      // 查询
      console.log(form)
      event.preventDefault()
      // this.$emit('hanlderSubmit', event, form)
    },
    remoteBefore(data, dataParams) {
      console.log(dataParams, 'dataParamsdataParamsdataParams')
      dataParams.data = {
        num: 'listOutBoundListToPrint',
        params: {
          ...dataParams.data,
        },
      }
      return dataParams
    },
    selectChange(selectedRowKeys, selectedRows) {
      // 勾选框
      console.log(selectedRowKeys, selectedRows)
      this.selectedRowKeys = selectedRowKeys
    },
    checkDetail(record) {
      // 查看详情
      this.detailVisible = true
      this.rowData = record
      this.$refs.detail.isvisible = true
      // this.$emit('changeClick', record)
    },
  },
}
</script>

<style>
.gridClass {
  margin-bottom: 12px;
}
.ant-tabletd {
  white-space: nowrap;
}
</style>
