<template>
  <div>
    <a-card :bordered="false" title="发运单" v-if="visible">
      <a-row :gutter="48" slot="extra">
        <a-col :md="48" :sm="48">
          <span class="table-page-search-submitButtons" style="float: right">
            <a-button style="margin-left: 8px" @click="handleCancel()">返回</a-button>
          </span>
        </a-col>
      </a-row>
      <title-divider title="采购单信息" width="120px"></title-divider>
      <detail-list title="" :col="3">
        <detail-list-item term="单号">{{ record.billNo }}</detail-list-item>
        <detail-list-item term="项目名称">{{ record.projectName }}</detail-list-item>
        <detail-list-item term="公司名称">{{ record.companyName }}</detail-list-item>
        <detail-list-item term="数量">{{ record.quantity }}</detail-list-item>
        <detail-list-item term="已发数量">{{ record.dispatchedQuantity }}</detail-list-item>
        <detail-list-item term="未发数量">{{ record.quantity - record.dispatchedQuantity }}</detail-list-item>
      </detail-list>
      <title-divider title="发运单" width="100px"></title-divider>
      <div class="table-page-search-wrapper" @keyup.enter="handleEnter">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="关键字">
                <a-input v-model="queryParam.keyword" placeholder="请输入名称/类型名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="8 || 24" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table1.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button v-if="$auth('purchase-purchase-dispatch-orders-add') && !endFlag " type="primary" icon="plus" @click="handleAdd">新增</a-button>
        <a-button style="margin-left: 8px" v-if="$auth('purchase-purchase-dispatch-orders-export')" type="primary" icon="download" @click="doExport">导出</a-button>
        <a-dropdown v-action:edit v-if="selectedRowKeys.length > 0 && $auth('purchase-purchase-dispatch-orders-del')">
          <a-menu slot="overlay">
            <a-popconfirm title="是否要删除所选数据？" @confirm="batchDelete()">
              <a-menu-item key="1"><a-icon type="delete" /><a>删除</a></a-menu-item>
            </a-popconfirm>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <s-table
        ref="table1"
        size="small"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :scroll="{x: 1, y: BaseTool.Constant.scrollY }"
        :alert="options.alert"
        :rowSelection="options.rowSelection"
        showPagination="auto"
      >
        <span slot="action" slot-scope="record">
          <template>
            <a @click="handleView(record)">查看</a>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && (user.userId === record.purchaserId || user.userId === record.shipperId) && record.status === DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DFY"
              @click="handleEdit(record)"
            >修改</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-del') && (user.userId === record.purchaserId || user.userId === record.shipperId) && record.status === DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DFY"
              :type="2"
              title="是否要删除该条数据？"
              @confirm="batchDelete(record.id)">删除</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-del') && (user.userId === record.purchaserId || user.userId === record.shipperId) && record.status === DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DFY"
              :type="2"
              title="初验完成操作过后将无法更改，确认进行该操作吗？？"
              @confirm="handleCheck(record)">初验完成</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && record.status > DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DFY && record.containerFlag"
              @click="doExport(record.id)"
            >导出发运明细</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && (user.userId === record.purchaserId || user.userId === record.shipperId) && record.status > DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DFY && record.status < DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DRK && record.containerFlag"
              @click="doImport(record.id)"
            >导入发运明细</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && (user.userId === record.purchaserId || user.userId === record.shipperId) && record.status > DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DFY && record.containerFlag"
              @click="handleDispatchContainer(record)"
            >装箱</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-del') && (user.userId === record.purchaserId || user.userId === record.shipperId || user.userId === record.receiverId) && record.status === DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DDG && record.containerFlag"
              :type="2"
              title="到港操作过后将无法更改，确认进行该操作吗？？"
              @confirm="handleReached(record.id)">到港</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && (user.userId === record.purchaserId || user.userId === record.shipperId || user.userId === record.receiverId) && record.status < DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DRKYS && record.status > DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DFY && record.containerFlag "
              @click="handleDispatchInfo(record)"
            >发运费用</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && (user.userId === record.purchaserId || user.userId === record.shipperId || user.userId === record.receiverId) && record.status === DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DRK && record.landFlag"
              @click="handleLandDispatch(record)"
            >陆运</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && (user.userId === record.purchaserId || user.userId === record.shipperId || user.userId === record.receiverId) && record.status === DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DRK"
              @click="handleInbound(record)"
            >提交入库</operation-button>
            <operation-button
              v-if="$auth('purchase-purchase-dispatch-orders-edit') && (user.userId === record.purchaserId || user.userId === record.shipperId || user.userId === record.receiverId) && record.quantityErrorFlag"
              :type="2"
              title="数量异常处理提交后将无法更改，确认进行该操作吗？"
              @confirm="handleQuantityErrorFlag(record)"
            >数量异常处理</operation-button>
          </template>
        </span>
      </s-table>
    </a-card>
    <base-form ref="baseModal" @ok="handleOk"/>
    <base-choose-form ref="baseChooseModal" @ok="handleOk"/>
    <dispatch-form ref="dispatchModal" @ok="handleOk"/>
    <inbound-form ref="inboundModal" @ok="handleOk"/>
    <land-dispatch-form ref="landDispatchModal" @ok="handleOk"/>
    <detail ref="detailModal" @ok="handleOk"/>
    <purchase-dispatch-container ref="dispatchContainer" @ok="handleOk"/>
    <import-form ref="importModal" @ok="handleOk"></import-form>
  </div>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseForm from './modules/BaseForm'
import BaseChooseForm from './modules/BaseChooseForm'
import DispatchForm from './modules/DispatchForm'
import InboundForm from './modules/InboundForm'
import LandDispatchForm from './modules/LandDispatchForm'
import Detail from './modules/Detail'
import { getPurchaseDispatchOrderPage, deletePurchaseDispatchOrders, fetchPurchaseDispatchOrder, exportPurchaseDispatchOrder, updatePurchaseDispatchOrderInfo, confirmUpdateQuantityForInStore } from '@/api/purchase/purchase-dispatch-order'
import DetailList from '@/components/tools/DetailList'
import PurchaseDispatchContainer from '@/views/purchase/purchase-dispatch-container/PurchaseDispatchContainer'
import DictCache from '@/utils/dict'
import ImportForm from '@/views/purchase/purchase-dispatch-order-list/modules/ImportForm'
import { exportPurchaseDispatchOrderList } from '@/api/purchase/purchase-dispatch-order-list'
const DetailListItem = DetailList.Item
export default {
  name: 'PurchaseDispatchOrderList',
  components: {
    STable,
    Ellipsis,
    BaseForm,
    BaseChooseForm,
    DispatchForm,
    DetailList,
    InboundForm,
    ImportForm,
    DetailListItem,
    LandDispatchForm,
    PurchaseDispatchContainer,
    Detail
  },
  data () {
    return {
      // 查询参数
      queryParam: {
      },
      record: {},
      visible: false,
      purchaseOrderId: '-1',
      user: this.$store.getters.userInfo,
      isCreated: false,
      endFlag: false,
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          checked: true,
          width: 70,
          customRender: (text, record, index) => {
            return `${(this.$refs.table1.localPagination.current - 1) * this.$refs.table1.localPagination.pageSize + index + 1}`
          }
        },
        {
          title: '单号',
          dataIndex: 'billNo',
          checked: true,
          width: 200
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          checked: true,
          width: 150
        },
        {
          title: '公司名称',
          dataIndex: 'companyName',
          width: 150
        },
        {
          title: '发货日期',
          dataIndex: 'dispatchDate',
          checked: true,
          width: 120
        },
        {
          title: '始发地国家',
          dataIndex: 'originCountryId',
          width: 120,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.countryMap, text)
          }
        },
        {
          title: '始发地国家地址',
          dataIndex: 'originCountryAddress',
          width: 120
        },
        {
          title: '目的地国家',
          dataIndex: 'destinationCountryId',
          checked: true,
          width: 150,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.countryMap, text)
          }

        },
        {
          title: '目的地地址',
          dataIndex: 'destinationCountryAddress',
          checked: true,
          width: 150
        },
        {
          title: '采购员名称',
          dataIndex: 'purchaserName',
          width: 120,
          checked: true
        },
        {
          title: '采购员联系方式',
          dataIndex: 'purchaserPhone',
          width: 120,
          checked: true
        },
        {
          title: '发货员名称',
          dataIndex: 'shipperName',
          width: 120,
          checked: true
        },
        {
          title: '发货员联系方式',
          dataIndex: 'shipperPhone',
          width: 120,
          checked: true
        },
        {
          title: '收货员名称',
          dataIndex: 'receiverName',
          width: 120,
          checked: true
        },
        {
          title: '收货员联系方式',
          dataIndex: 'receiverPhone',
          width: 120,
          checked: true
        },
        {
          title: '发运方式',
          dataIndex: 'dispatchType',
          width: 100,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.dispatchTypeMap, text)
          }
        },
        {
          title: '存货位置',
          dataIndex: 'inventoryLocation',
          width: 150,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.storePlaceMap, text)
          }
        },

        {
          title: '数量',
          dataIndex: 'quantity',
          width: 100,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '已发数量',
          dataIndex: 'dispatchedQuantity',
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '未发数量',
          dataIndex: 'notDispatchQuantity',
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '发运邮寄单号',
          dataIndex: 'mailingNum',
          width: 100,
          checked: true
        },
        {
          title: '发运费用(按项目主币)',
          dataIndex: 'accountTotalMoneyOther',
          width: 150,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        // {
        //   title: '运费',
        //   dataIndex: 'freightFee',
        //   width: 100,
        //   customRender: (text, record, index) => {
        //     return this.BaseTool.Amount.formatter(text)
        //   }
        // },
        // {
        //   title: '保险费',
        //   dataIndex: 'insuranceFee',
        //   width: 100,
        //   customRender: (text, record, index) => {
        //     return this.BaseTool.Amount.formatter(text)
        //   }
        // },
        // {
        //   title: '运杂费',
        //   dataIndex: 'dispatchSurcharge',
        //   width: 100,
        //   customRender: (text, record, index) => {
        //     return this.BaseTool.Amount.formatter(text)
        //   }
        // },
        // {
        //   title: '关税',
        //   dataIndex: 'tariff',
        //   width: 100,
        //   customRender: (text, record, index) => {
        //     return this.BaseTool.Amount.formatter(text)
        //   }
        // },
        // {
        //   title: '清关费',
        //   dataIndex: 'clearanceCharge',
        //   width: 100,
        //   customRender: (text, record, index) => {
        //     return this.BaseTool.Amount.formatter(text)
        //   }
        // },
        // {
        //   title: '港杂税',
        //   dataIndex: 'portSurcharge',
        //   width: 100,
        //   customRender: (text, record, index) => {
        //     return this.BaseTool.Amount.formatter(text)
        //   }
        // },
        // {
        //   title: '二次转运费',
        //   width: 100,
        //   dataIndex: 'secondaryTransportationFee',
        //   customRender: (text, record, index) => {
        //     return this.BaseTool.Amount.formatter(text)
        //   }
        // },
        {
          title: '差额情况',
          dataIndex: 'differenceType',
          width: 100,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.differenceTypeMap, text)
          }
        },
        {
          title: '入库仓库名称',
          dataIndex: 'warehouseName',
          width: 100,
          checked: true
        },
        {
          title: '入库原因',
          dataIndex: 'enterReason',
          width: 100,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.enterReasonMap, text)
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          checked: true,
          fixed: 'right',
          width: 100,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.statusCustomRenderDict(this, text, record,
              this.DictCache.COLOR.PURCHASE_DISPATCH_ORDER_STATUS, this.statusMap)
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 100
        },
        {
          title: '创建人名称',
          dataIndex: 'createdUserName',
          width: 100
        },
        {
          title: '创建时间',
          dataIndex: 'createdTime',
          width: 100
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          fixed: 'right',
          checked: true,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 下拉框map
      statusMap: {},
      storePlaceMap: {},
      dispatchTypeMap: {},
      differenceTypeMap: {},
      enterReasonMap: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const user = this.$store.getters.userInfo
        const roleCodes = user.roleCodes.join(',')
        parameter = {
          ...parameter,
          ...this.queryParam,
          purchaseOrderId: this.purchaseOrderId,
          projectId: roleCodes.indexOf('FGS_') > -1 ? null : user.projectId,
          dataScope: {
            sortBy: 'asc,desc',
            sortName: 'status,update_time'
          }
        }
        return getPurchaseDispatchOrderPage(Object.assign(parameter, this.queryParam))
          .then(res => {
            return res.data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      moneyTypeMap: {},

      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  created () {
    // 下拉框map
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_DISPATCH_STATUS)
    this.dispatchTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.DISPATCH_TYPE)
    this.differenceTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_DIFF_TYPE)
    this.enterReasonMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.IN_STORE_FORM_TYPE)
    this.storePlaceMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_STORE_PLACE)
    this.countryMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_USER_COUNTRY)
    this.moneyTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.MONEY_TYPE)
    this.tableOption()
  },
  methods: {
    base (record) {
      this.visible = true
      this.record = record
      this.endFlag = (record.status === DictCache.VALUE.PURCHASE_ORDER_STATUS.PURCHASE_APPLY_STATUS_YWJ)
      this.purchaseOrderId = record.id
      if (this.isCreated) {
        this.handleOk()
      } else {
        this.tableOption()
        this.isCreated = true
      }
    },
    handleCheck (record) {
      const id = record.id
      const status = record.containerFlag ? this.DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DZX : this.DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DRK
      updatePurchaseDispatchOrderInfo({ id: id, submitType: status }).then(res => {
        this.handleOk()
      })
    },
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: false,
                name: record.id
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleDispatchContainer (record) {
      fetchPurchaseDispatchOrder({ id: record.id }).then(res => {
        const modal = this.$refs.dispatchContainer
        this.visible = false
        modal.base(res.data)
      })
    },
    handleReached (id) {
      updatePurchaseDispatchOrderInfo({ id: id, submitType: this.DictCache.VALUE.PURCHASE_DISPATCH_STATUS.PURCHASE_DISPATCH_STATUS_DRK }).then(res => {
        this.handleOk()
      })
    },
    handleDispatchInfo (record) {
      fetchPurchaseDispatchOrder({ id: record.id }).then(res => {
        const modal = this.$refs.dispatchModal
        this.visible = false
        modal.base(res.data)
      })
    },
    handleInbound (record) {
      fetchPurchaseDispatchOrder({ id: record.id }).then(res => {
        const modal = this.$refs.inboundModal
        this.visible = false
        modal.base(res.data)
      })
    },
    handleQuantityErrorFlag (record) {
      confirmUpdateQuantityForInStore({ id: record.id }).then(res => {
        this.$refs.table1.refresh()
      })
    },
    handleLandDispatch (record) {
      fetchPurchaseDispatchOrder({ id: record.id }).then(res => {
        const modal = this.$refs.landDispatchModal
        modal.base(res.data)
      })
    },
    batchDelete (id) {
      let ids = []
      if (this.BaseTool.String.isBlank(id)) {
        const length = this.selectedRows.length
        if (length === 0) {
          this.$message.info('请选择要删除的记录')
          return
        }
        ids = this.selectedRows.map(item => item.id)
      } else {
        ids = [id]
      }
      deletePurchaseDispatchOrders(ids).then(res => {
        this.$message.info('删除成功')
        this.handleOk()
        this.$refs.table1.clearSelected()
      })
    },
    handleAdd () {
      this.visible = false
      this.$refs.baseModal.base(null, this.purchaseOrderId)
    },
    handleEdit (record) {
      fetchPurchaseDispatchOrder({ id: record.id }).then(res => {
        const modal = this.$refs.baseChooseModal
        this.visible = false
        modal.base(res.data)
      })
    },
    handleView (record) {
      fetchPurchaseDispatchOrder({ id: record.id }).then(res => {
        const modal = this.$refs.detailModal
        this.visible = false
        modal.base(res.data)
      })
    },
    handleOk () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.table1.refresh()
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
        purchaseOrderId: this.purchaseOrderId
      }
      this.$refs.table1.refresh(true)
    },
    doImport (dispatchOrderId) {
      this.$refs.importModal.base(dispatchOrderId)
    },
    doExport (dispatchOrderId) {
      const parameter = {
        ...this.queryParam,
        dispatchOrderId: dispatchOrderId
      }
      exportPurchaseDispatchOrderList(parameter).then(file => {
        this.BaseTool.UPLOAD.downLoadExportExcel(file)
      })
    },
    handleEnter () {
      this.$refs.table1.refresh(true)
    },
    handleCancel (values) {
      this.visible = false
      this.$emit('ok', values)
    }
  }
}
</script>
