<template>
  <div class="transfersPrintList-wrap">
    <a-card size="small" :bordered="false" :class="currentTab==2 ? 'searchBox' : 'searchBoxNormal'">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" id="transfersPrintList-form" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate id="transfersPrintList-time" ref="rangeDate" :value="time" @change="dateChange" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调往对象">
                <a-input id="transfersPrintList-targetName" v-model.trim="queryParam.targetName" allowClear placeholder="请输入调往对象"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调拨单号">
                <a-input id="transfersPrintList-allocateNo" v-model.trim="queryParam.allocateNo" allowClear placeholder="请输入调拨单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-if="currentTab==2&&!isShowCustomerSearch">
              <a-form-item label="业务状态">
                <v-select
                  v-model="queryParam.state"
                  ref="state"
                  id="transfersPrintList-state"
                  code="ALLOCATE_STATUS"
                  placeholder="请选择业务状态"
                  allowClear
                ></v-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24" v-if="currentTab==1 ||(currentTab==2&&isShowCustomerSearch)">
                <a-form-item label="业务状态">
                  <v-select
                    v-model="queryParam.state"
                    ref="state"
                    id="transfersPrintList-state"
                    code="ALLOCATE_STATUS"
                    placeholder="请选择业务状态"
                    allowClear
                  ></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-if="currentTab == 1">
                <a-form-item label="打印状态">
                  <v-select
                    v-model="queryParam.printState"
                    ref="printState"
                    id="transfersPrintList-printState"
                    code="PRINT_STATUS"
                    placeholder="请选择打印状态"
                    allowClear
                  ></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="收货客户名称">
                  <dealerSearchList id="transfersPrintList-receiver" ref="receiverSn" @change="custChange"/>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowWarehouse">
                <a-form-item label="调出仓库">
                  <warehouse
                    v-model="queryParam.warehouseSn"
                    isPermission
                    id="transfersPrintList-warehouseSn"
                    placeholder="请选择调出仓库"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea id="transfersPrintList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="地区">
                  <Area id="transfersPrintList-shippingAddrProvinceSn" v-model="queryParam.shippingAddrProvinceSn" placeholder="请选择省"></Area>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-show="isShowCustomerSearch">
                <a-form-item label="客服">
                  <customerService ref="customerName" id="transfersPrintList-bizUserSn" v-model="queryParam.bizUserSn"></customerService>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="currentTab==2&&!isShowCustomerSearch ?24:6" :sm="24" :style="{textAlign: (currentTab==2&&!isShowCustomerSearch)?'center':''}">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="transfersPrintList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="transfersPrintList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px" id="transfersPrintList-advanced">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <div style="background-color: #fff;">
      <a-tabs v-model="currentTab" @change="changeTab" id="transfersPrintList-tabs">
        <a-tab-pane :key="1" tab="全部" id="transfersPrintList-tabs1">
        </a-tab-pane>
        <a-tab-pane :key="2" tab="待打印" id="transfersPrintList-tabs2">
        </a-tab-pane>
      </a-tabs>
    </div>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+84.5+'px' }"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ y: tableHeight }"
          bordered>
          <!-- 单号 -->
          <template slot="allocateNo" slot-scope="text, record">
            <span v-if="$hasPermissions('M_transferOut_detail')" :id="'transfersPrintList-allocateNo'+record.id" class="link-bule" @click="handleDetail(record)">{{ record.allocateNo }}</span>
            <span v-else>{{ record.allocateNo }}</span>
          </template>
          <!-- 打印状态 -->
          <template slot="printStatus" slot-scope="text, record">
            <span v-if="record.printState=='NO_PRINT'" :id="'transfersPrintList-printStatus'+record.id" class="link-bule" @click="editPrintStatus(record)">{{ record.printStateDictValue }}</span>
            <span v-else>{{ record.printStateDictValue }}</span>
          </template>
          <div slot="costTitle">
            <a-tooltip placement="top">
              <template slot="title">
                当调拨对象是经销商时，如果收货客户名称不为空，则按照收货客户的开单金额（授权价＋商户级别价），有经销权则使用授权价，没有经销权则使用商户级别价。
              </template>
              <span style="margin-right: 5px;">实际总售价</span> <a-icon type="question-circle" />
            </a-tooltip>
          </div>
          <!-- 操作 -->
          <template slot="action" slot-scope="text, record">
            <a-button
              size="small"
              type="link"
              v-if="record.printState == 'NO_PRINT'&&$hasPermissions('B_transferOut_type_print')"
              class="button-warning"
              @click="handlePrint(record)"
              :id="'transfersPrintList-printState-btn'+record.id">调拨分类打印</a-button>
            <a-button
              size="small"
              type="link"
              v-else-if="record.printState == 'PRINT'&&$hasPermissions('B_tfoPrint_record')"
              class="button-success"
              @click="handlePrintRecord(record)"
              :id="'transfersPrintList-printRecord-btn'+record.id">打印记录</a-button>
            <span v-else>--</span>
          </template>
        </s-table>
      </a-spin>
    </a-card>
    <!-- 打印导出 -->
    <print-modal
      v-drag
      :openModal="openModal"
      :itemData="itemData"
      showExplainInfo
      nowType="dbflPrint"
      @ok="handleOk"
      @close="openModal=false" />
    <!-- 打印记录 -->
    <recordModal v-drag ref="recordModal" modalTit="打印记录" :openModal="showRecordModal" @cancel="showRecordModal=false"></recordModal>
    <!-- 操作提示 -->
    <commonModal modalTit="操作提示" okText="暂不打印" :openModal="showPrintModal" @cancel="canselModal" @ok="updatePrintStatus">
      <div style="display:flex;flex-direction: column;align-items: center;">
        <div style="margin-bottom: 15px;font-size: 14px;">如需将打印状态回退至<strong>【暂不打印】</strong>,请点击下方按钮</div>
        <div style="line-height: 24px;text-align:left;">
          <div>调拨单号：{{ tipData&&tipData.allocateNo }}</div>
          <div>调往对象：{{ tipData&&tipData.targetName }}</div>
        </div>
      </div>
    </commonModal>
    <!-- 查看详情 -->
    <commonModal
      modalTit="调拨单详情"
      bodyPadding="10px"
      width="70%"
      :showFooter="false"
      :openModal="showDetailModal"
      @cancel="cancelDetail">
      <allocationDetailModal v-if="showDetailModal" :outBizSn="bizSn" />
    </commonModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import getDate from '@/libs/getDate.js'
import { printBase64Fun } from '@/libs/JGPrint.js'
// 组件
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import rangeDate from '@/views/common/rangeDate.vue'
import dealerSearchList from '@/views/common/dealerSearchList.vue'
import printModal from '@/views/allocationManagement/transferOut/printModal.vue'
import commonModal from '@/views/common/commonModal.vue'
import warehouse from '@/views/common/chooseWarehouse.js'
import customerService from '@/views/common/customerService'
import allocationDetailModal from '@/views/allocationManagement/transferOut/detail.vue'
import recordModal from './recordModal.vue'
// 接口
import { allocateBillList, allocateBillDetailPrint, updatePrintState } from '@/api/allocateBill'
export default {
  name: 'TransfersPrintList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, dealerSearchList, printModal, commonModal, recordModal, subarea, Area, allocationDetailModal, warehouse, customerService },
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      itemData: null, // 当前行数据
      bizSn: '', // 调拨sn
      showRecordModal: false, // 打印记录弹窗
      showPrintModal: false, // 打印弹窗
      showDetailModal: false, // 调拨单详情弹窗
      // 创建时间默认值
      time: [
        moment(getDate.getThreeMonthDays().starttime, 'YYYY-MM-DD'), // 开始时间
        moment(getDate.getCurrMonthDays().endtime, 'YYYY-MM-DD')// 几位数使劲
      ],
      //  查询条件
      queryParam: {
        beginDate: getDate.getThreeMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime, // 结束时间
        targetName: '', //  调往对象
        state: undefined, //  业务状态
        allocateNo: '', //  调拨单号
        receiverSn: undefined, // 收货客户名称
        checkStatus: undefined, // 选中状态
        warehouseSn: undefined, // 调出仓库
        printState: 'NO_PRINT', // 打印状态
        subareaArea: {
          subareaSn: undefined, // 区域
          subareaAreaSn: undefined// 分区
        },
        shippingAddrProvinceSn: undefined, // 选中省份
        bizUserSn: undefined// 客服
      },
      currentTab: 2, // tabs默认值
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        // 获取列表数据  有分页
        return allocateBillList(Object.assign(parameter, this.queryParam, { authWarehouseFlag: 1 })).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算表格序号
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      visibleAudit: false, // 审核弹窗
      openModal: false, //  打印弹框
      tipData: null// 操作提示回显数据
    }
  },
  computed: {
    // 表头
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨单号', scopedSlots: { customRender: 'allocateNo' }, align: 'center', width: '8%' },
        { title: '调往对象', dataIndex: 'targetName', width: '17%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '发货编号', dataIndex: 'sendNo', width: '4%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '发货说明', dataIndex: 'explainInfo', width: '14%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '收货客户名称', dataIndex: 'receiverName', width: '17%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '总数量', dataIndex: 'totalQty', width: '4%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '打印状态', scopedSlots: { customRender: 'printStatus' }, width: '5%', align: 'center' },
        { title: '允许打印时间', dataIndex: 'allowPrintTime', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '打印次数', dataIndex: 'printCount', width: '4%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '6%', align: 'center' }
      ]
      if (this.isShowWarehouse) {
        arr.splice(4, 0, { title: '调出仓库', dataIndex: 'warehouseName', width: '6%', align: 'center', customRender: function (text) { return text || '--' } })
      }

      if (this.$hasPermissions('M_transfersPrintList_salesPrice')) { //  售价权限
        arr.splice(9, 0, { slots: { title: 'costTitle' }, dataIndex: 'receiveTotalAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(10, 0, { title: '易损件售价', dataIndex: 'receiveYsjTotalAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(11, 0, { title: '电池售价', dataIndex: 'receiveDcTotalAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(12, 0, { title: '机油售价', dataIndex: 'receiveJyTotalAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }

      return arr
    }
  },
  methods: {
    // 收货客户名称 change
    custChange (val) {
      if (val.row) {
        this.queryParam.receiverSn = val.row.dealerSn
        this.queryParam.receiverName = undefined
      } else {
        this.queryParam.receiverSn = undefined
        this.queryParam.receiverName = val.key
      }
    },
    // tabs事件
    changeTab (v) {
      this.currentTab = v
      this.resetSearchForm()
    },
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    // 区域分区
    subareaChange (val) {
      this.queryParam.subareaArea = {
        subareaSn: val[0] ? val[0] : undefined,
        subareaAreaSn: val[1] ? val[1] : undefined
      }
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate(this.time)
      this.queryParam.beginDate = getDate.getThreeMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.targetName = ''
      this.queryParam.state = undefined
      this.queryParam.allocateNo = ''
      this.queryParam.receiverName = ''
      this.queryParam.receiverSn = undefined
      this.queryParam.warehouseSn = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.subareaArea.subareaSn = undefined
      this.queryParam.subareaArea.subareaAreaSn = undefined
      this.queryParam.shippingAddrProvinceSn = undefined
      this.$refs.receiverSn.resetForm()
      if (this.advanced) {
        this.$refs.subarea.clearData()
      }
      this.queryParam.printState = this.currentTab == 2 ? 'NO_PRINT' : undefined
      this.$refs.table.refresh(true)
    },
    // 分类打印
    handlePrint (row) {
      this.itemData = row
      this.openModal = true
    },
    // 打印记录
    handlePrintRecord (row) {
      this.showRecordModal = true
      this.$refs.recordModal.setData(row, {
        billType: 'ALLOCATE',
        billSn: row.allocateSn
      })
    },
    // 确定打印
    handleOk (objs) {
      const _this = this
      const params = JSON.parse(JSON.stringify(objs))
      delete params.type
      _this.$store.state.app.curActionPermission = 'B_transferOut_type_print'
      _this.spinning = true
      printBase64Fun(
        allocateBillDetailPrint,
        params,
        objs.isPreview ? 'preview' : 'print',
        '调拨分类',
        (res) => {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
          if (res && res.status == 200) {
            _this.$refs.table.refresh()
            _this.$message.info(res.message)
          }
        }, {
          billType: 'ALLOCATE',
          billSn: objs.allocateSn,
          billNo: objs.allocateNo,
          printType: '调拨分类打印'
        })
    },
    //  详情
    handleDetail (row) {
      this.$store.state.app.curActionPermission = 'M_transferOut_detail'
      this.bizSn = row.allocateSn
      this.showDetailModal = true
    },
    // 关闭详情弹窗
    cancelDetail () {
      this.showDetailModal = false
      this.$store.state.app.curActionPermission = ''
      this.bizSn = null
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 266
    },
    // 状态打印弹窗
    editPrintStatus (item) {
      this.tipData = item
      this.$nextTick(() => {
        this.showPrintModal = true
      })
    },
    // 关闭操作提示弹窗
    canselModal () {
      this.showPrintModal = false
      this.resetSearchForm()
    },
    // 操作提示成功呢
    updatePrintStatus () {
      const _this = this
      _this.spinning = true
      const ajax_data = {
        allocateSn: _this.tipData.allocateSn,
        printState: 'UNABLE_PRINT'
      }
      updatePrintState(ajax_data).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.canselModal()
        }
        _this.spinning = false
      })
    }
  },
  watch: {
    // 展开关闭 监听表格高度变化
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
<style lang="less">
  .transfersPrintList-wrap{
    .ant-tabs-bar{
      margin: 0;
    }
  }
</style>
