<template>
  <div class="salesReturnDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesReturnDetail-cont">
        <template slot="subTitle">
          <a id="salesEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ detailData&&detailData.salesReturnBillNo }}</span>
          <span style="margin: 0 10px;color: #666;">客户名称：{{ detailData&&detailData.buyerName }}</span>
          <a-button size="small" type="link" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra">
          <a-button
            key="3"
            type="default"
            class="button-info"
            id="salesReturnEdit-preview-btn"
            v-if="$hasPermissions('B_salesReturnPrint')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('preview')">打印预览</a-button>
          <a-button
            key="2"
            type="primary"
            class="button-info"
            id="salesReturnEdit-print-btn"
            v-if="$hasPermissions('B_salesReturnPrint')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('print')">快捷打印</a-button>
          <a-divider type="vertical" />
          <a-button
            key="1"
            type="default"
            class="button-warning"
            id="salesReturnEdit-export-btn"
            v-if="$hasPermissions('B_salesReturnExport')"
            :disabled="chooseLoadData.length==0"
            @click="handlePrint('export')">导出Excel</a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="salesReturnDetail-cont" v-show="showDetail">
        <a-descriptions size="small" :column="4">
          <a-descriptions-item label="单据来源">{{ detailData&&detailData.salesReturnBillSourceDictValue || '--' }}</a-descriptions-item>
          <a-descriptions-item label="销售退货单号">{{ detailData&&detailData.salesReturnBillNo || '--' }}</a-descriptions-item>
          <a-descriptions-item label="退货仓库">{{ detailData&&detailData.warehouseName || '--' }}</a-descriptions-item>
          <a-descriptions-item label="客户名称">{{ detailData&&detailData.buyerName || '--' }}</a-descriptions-item>
          <a-descriptions-item label="客户采退申请单号">{{ detailData&&detailData.purchaseReturnApplyNo || '--' }}</a-descriptions-item>
          <a-descriptions-item label="是否同步给客户">{{ detailData&&detailData.syncFlag ? ['否', '是'][detailData.syncFlag] : '--' }}</a-descriptions-item>
          <a-descriptions-item label="业务状态">{{ detailData&&detailData.billStatusDictValue || '--' }}</a-descriptions-item>
          <a-descriptions-item label="退货类别">{{ detailData&&detailData.goodFlagDictValue || '--' }}</a-descriptions-item>
          <a-descriptions-item label="退货类型">{{ detailData&&detailData.salesReturnTypeDictValue || '--' }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ detailData&&detailData.createDate || '--' }}</a-descriptions-item>
          <a-descriptions-item label="审核时间">{{ detailData&&detailData.auditTime || '--' }}</a-descriptions-item>
          <a-descriptions-item label="附件" v-if="detailData" :span="3">
            <a target="_blank" style="color: #00aaff;text-decoration: underline;margin-right: 15px;" :href="item.filePath" v-for="item in detailData.attachmentList" :key="item.id">
              {{ item.fileName }}
            </a>
            <span v-if="detailData.attachmentList.length==0">--</span>
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-card size="small" :bordered="false" class="pages-wrap">
        <a-tabs v-model="curTab" @change="changeTab">
          <a-tab-pane :key="1" tab="产品明细" force-render>
            <a-alert style="margin-bottom: 10px;" type="info">
              <div slot="message" class="total-bar">
                <div>
                  <span>申请退货数量：{{ detailData&&(detailData.totalInitialQty || detailData.totalInitialQty==0) ? detailData.totalInitialQty : '--' }}；</span>
                  <span>仓库实收数量：{{ detailData&&(detailData.totalReceiveQty || detailData.totalReceiveQty==0) ? detailData.totalReceiveQty : '--' }}；</span>
                  <span>坏件数量：{{ detailData&&(detailData.totalBadQty || detailData.totalBadQty==0) ? detailData.totalBadQty : '--' }}；</span>
                  <span>良品数量：{{ detailData&&(detailData.totalGoodQty || detailData.totalGoodQty==0) ? detailData.totalGoodQty : '--' }}；</span>
                  <span>返库数量：{{ detailData&&(detailData.totalBackStockQty || detailData.totalBackStockQty==0) ? detailData.totalBackStockQty : '--' }}；</span>
                  <span v-if="$hasPermissions('B_salesReturnDetail_salesPrice')">
                    参考退货金额：{{ detailData&&(detailData.initialAmount || detailData.initialAmount==0) ? toThousands(detailData.initialAmount) : '--' }}；
                    实际退货金额：{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}；
                  </span>
                </div>
              </div>
            </a-alert>
            <div style="display:flex;align-items:center;justify-content: space-between;margin-bottom: 10px;">
              <div>说明：红色行表示收货时新增的产品；黄色表示客服确认时新增的产品；退货原因文字显示红色表示退货原因和退货类别不一致；</div>
            </div>
            <!-- 列表 -->
            <s-table
              class="sTable"
              :rowClassName="(record, index) => record.addFlag == '1' ? (record.addType == 'WAREHOUSE_RECEIVE'?'redBg-row':'orgBg-row'):''"
              ref="table"
              size="small"
              :pageSize="10"
              :rowKey="record => record.id"
              :columns="columns"
              :data="loadData"
              :scroll="{ x: 'calc(700px + 50%)'}"
              bordered>
              <!-- 退货原因 -->
              <template slot="returnReason" slot-scope="text, record">
                <span title="退货原因和退货类别不一致" :style="{color:record.needHandleFlag==1?'red':''}">{{ record.returnReason||'--' }}</span>
              </template>
            </s-table>
          </a-tab-pane>
          <a-tab-pane :key="2" tab="审核进度" >
            <auditDetail v-if="$hasPermissions('B_salesReturnAudit')" ref="auditDetail" businessType="SALES_RETURN" :itemSn="$route.params.sn"></auditDetail>
            <span v-else>您没有权限查看审核进度</span>
          </a-tab-pane>
          <a-tab-pane :key="3" tab="操作记录">
            <s-table
              class="sTable"
              ref="operateTable"
              size="small"
              :rowKey="record => record.id"
              :columns="operateColumns"
              :data="operateLoadData"
              bordered></s-table>
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </a-spin>
    <!-- 打印导出 -->
    <print-modal
      :openModal="openModal"
      :showPrice="nowType=='export'?$hasPermissions('B_salesReturnExport_salesPrice'):$hasPermissions('B_salesReturnPrint_salesPrice')"
      :itemData="detailData"
      :nowType="nowType"
      @ok="handleOk"
      @close="openModal=false" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import { printFun, exportExcel } from '@/libs/JGPrint.js'
import auditDetail from './auditDetail.vue'
import printModal from './printModal.vue'
import { salesReturnDetail, salesReturnChangeLogList, salesReturnPrint, salesReturnExport } from '@/api/salesReturn'
import { salesReturnDetailList } from '@/api/salesReturnDetail'
export default {
  name: 'SalesReturnDetail',
  mixins: [commonMixin],
  components: { STable, VSelect, auditDetail, printModal },
  data () {
    return {
      spinning: false,
      disabled: false,
      openModal: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, { salesReturnBillSn: this.$route.params.sn })
        return salesReturnDetailList(params).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.chooseLoadData = data.list
            this.disabled = false
          }
          return data
        })
      },
      chooseLoadData: [],
      detailData: null, //  详情数据
      nowType: '',
      visibleAudit: false,
      spinningAudit: false,
      showDetail: false,
      curTab: 1,
      queryStrList: [
        { code: 0, text: '不显示退货单价/金额' },
        { code: 1, text: '显示——按照申请退货数量计算' },
        { code: 2, text: '显示——按照仓库实收数量计算' }
      ],
      showFlag: undefined,
      // 操作记录
      operateColumns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '操作时间', dataIndex: 'createDate', align: 'center', width: '10%', customRender: function (text) { return text || '--' } },
        { title: '操作人员', dataIndex: 'changeUserName', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作类型', dataIndex: 'logTypeName', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作内容', dataIndex: 'logContent', width: '70%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      operateLoadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, { salesReturnBillSn: this.$route.params.sn })
        return salesReturnChangeLogList(params).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
          }
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', align: 'center', width: '6%', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '14%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '申请退货数量', dataIndex: 'initialQty', align: 'center', width: '6%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库实收数量', dataIndex: 'receiveQty', align: 'center', width: '6%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '坏件数量', dataIndex: 'badQty', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '良品数量', dataIndex: 'goodQty', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '返库数量', dataIndex: 'backStockQty', align: 'center', width: '5%', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货原因', dataIndex: 'returnReason', width: '8%', align: 'center', scopedSlots: { customRender: 'returnReason' } },
        { title: '备注', dataIndex: 'returnReasonRemarks', width: '10%', align: 'center', customRender: function (text) { return text || '--' } }
      ]
      if (this.$hasPermissions('B_salesReturnDetail_salesPrice') && this.showFlag != 0) { //  售价权限
        arr.splice(11, 0, { title: '参考退货单价', dataIndex: 'initialPrice', align: 'right', width: '6%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(12, 0, { title: '参考退货金额', dataIndex: 'initialAmount', align: 'right', width: '6%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(13, 0, { title: '实际退货单价', dataIndex: 'price', align: 'right', width: '6%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(14, 0, { title: '实际退货金额', dataIndex: 'totalAmount', align: 'right', width: '6%', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
        arr.splice(15, 0, { title: '实际退货单价说明', dataIndex: 'priceRemark', width: '10%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      return arr
    }
  },
  methods: {
    //  返回
    handleBack () {
      if (this.$route.query.path == 'receiveCheck') {
        this.$router.push({ name: 'receiveCheckList' })
      } else if (this.$route.query.path == 'returnSchedule') {
        this.$router.push({ name: 'returnSchedule' })
      } else {
        this.$router.push({ name: 'salesReturnList' })
      }
    },
    //  详情
    getDetail () {
      this.curTab = 1
      salesReturnDetail({ sn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
        } else {
          this.detailData = null
        }
      })
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      const a = ['WAIT_CUSTOMER_SERVICE_CONFIRM', 'WAIT_FINANCIAL_AUDIT', 'FINANCIAL_REJECT', 'FINISH'].find(item => item == this.detailData.billStatus)
      this.nowType = type
      // 选择是否导出价格
      if (a) {
        if (type == 'export') {
          if (this.$hasPermissions('B_salesReturnDetail_salesPrice')) {
            this.openModal = true
          } else {
            this.handleOk({ priceType: 'SALES_RETURN_REASON' })
          }
        } else {
          this.openModal = true
        }
      } else {
        this.handleOk({ priceType: 'SALES_RETURN_REASON' })
      }
    },
    // 确定打印或预览
    handleOk (objs) {
      const _this = this
      const params = { salesReturnBillSn: this.$route.params.sn, ...objs }
      _this.spinning = true
      // 导出
      if (this.nowType == 'export') {
        this.$store.state.app.curActionPermission = 'B_salesReturnExport'
        exportExcel(salesReturnExport, params, '销售退货', function () {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
        })
      } else {
        this.$store.state.app.curActionPermission = 'B_salesReturnPrint'
        // 打印或预览
        printFun(salesReturnPrint, params, this.nowType, '销售退货', () => {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
        })
      }
    },
    changeTab (v) {
      this.$nextTick(() => {
        if (v == 1) {
          this.$refs.table.refresh(true)
        }
        if (v == 2) {
          this.$refs.auditDetail.refresh()
        }
        if (v == 3) {
          this.$refs.operateTable.refresh(true)
        }
      })
    },
    pageInit () {
      this.getDetail()
      if (!this.disabled) {
        this.$refs.table.refresh(true)
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
.salesReturnDetail-wrap {
  .salesReturnDetail-cont {
    margin-bottom: 8px;
  }
  .pages-wrap{
    height: calc(100vh - 145px)
  }
  .footer-cont{
    margin-top: 5px;
    text-align: center;
  }
  .redBg-row{
    background-color: #f5beb4;
  }
  .orgBg-row{
    background-color: #fffca2;
  }
}
</style>
