<template>
  <div>
    <a-card size="small" :bordered="false" class="salesReturnDetailList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="urchaseDetailReturn-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="退货完成日期" prop="time">
                <rangeDate ref="rangeDate" id="urchaseDetailReturn-time" :value="queryParam.time" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品编码">
                <a-input id="urchaseDetailReturn-productCode" v-model.trim="queryParam.product.code" allowClear placeholder="请输入产品编码"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="采购退货单号">
                <a-input id="urchaseDetailReturn-sparePartsReturnNo" v-model.trim="queryParam.sparePartsReturnNo" allowClear placeholder="请输入采购退货单号"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="供应商名称">
                  <supplier id="urchaseDetailReturn-supplierSn" isPermission v-model="queryParam.supplier.supplierSn" @change="getSupplierName" placeholder="请输入供应商名称"></supplier>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="退货原因">
                  <v-select
                    id="urchaseDetailReturn-returnReason"
                    v-model="queryParam.returnReason"
                    ref="returnReason"
                    code="SPARE_PARTS_RETURN_REASON"
                    placeholder="请选择退货原因"
                    allowClear></v-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品名称">
                  <a-input id="urchaseDetailReturn-productName" v-model.trim="queryParam.product.name" allowClear placeholder="请输入产品名称"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品品牌">
                  <ProductBrand id="urchaseDetailReturn-productBrandSn" v-model="queryParam.product.productBrandSn"></ProductBrand>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="品牌分类">
                  <v-select code="BRAND_TYPE" id="urchaseDetailReturn-productBrandTypeSn" v-model="queryParam.product.brandType" allowClear placeholder="请选择品牌分类"></v-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="出库仓库">
                  <chooseWarehouse isPermission id="urchaseDetailReturn-warehouse" ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <AreaList id="urchaseDetailReturn-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button style="margin-left: 5px" type="primary" @click="handleSearch" :disabled="disabled" id="urchaseDetailReturn-refresh">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="urchaseDetailReturn-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_urchaseDetailReturn_export')"
                id="urchaseDetailReturn-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <!-- 列表 -->
    <a-card size="small" :bordered="false" class="salesReturnDetailList-wrap">
      <a-spin :spinning="spinning" tip="Loading...">
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ x: 2960 ,y: tableHeight-30 }"
          :defaultLoadData="false"
          bordered>
          <!-- 附件 -->
          <template slot="attachmentList" slot-scope="text, record">
            <span v-if="record.attachmentList && record.attachmentList.length > 0">
              <a
                :id="'urchaseDetailReturn-link'+record.id"
                target="_blank"
                style="color: #00aaff;text-decoration: underline;margin-right: 15px;"
                :href="item.filePath"
                v-for="item in record.attachmentList"
                :key="item.id"
              >
                {{ item.fileName }}
              </a>
            </span>
            <span v-else>--</span>
          </template>
          <template slot="footer">
            <a-row :gutter="15">
              <a-col :md="4" :sm="24">申请退货数量：{{ (totalData && (totalData.qty || totalData.qty==0)) ? totalData.qty : '--' }}</a-col>
              <a-col :md="4" :sm="24" v-if="$hasPermissions('M_urchaseDetailReturnList_costPrice')">退货金额：{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? toThousands(totalData.totalCost,2) : '--' }}</a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import supplier from '@/views/common/supplier.js'
import reportModal from '@/views/common/reportModal.vue'
import AreaList from '@/views/common/areaList.js'
import ProductBrand from '@/views/common/productBrand.js'
import chooseWarehouse from '@/views/common/chooseWarehouse'
// 接口
import { sparePartsReturnDetailReportList, sparePartsReturnDetailReportStat, sparePartsReturnReportExportDetail } from '@/api/reportData'
export default {
  name: 'UrchaseDetailReturnList',
  mixins: [commonMixin],
  components: { STable, VSelect, rangeDate, supplier, ProductBrand, reportModal, AreaList, chooseWarehouse },
  data () {
    return {
      spinning: false,
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      showExport: false, // 导出弹窗
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      //  查询条件
      queryParam: {
        // 退货完成日期 默认值
        time: [
          getDate.getCurrMonthDays().starttime,
          getDate.getCurrMonthDays().endtime
        ],
        beginDate: getDate.getCurrMonthDays().starttime, // 开始日期
        endDate: getDate.getCurrMonthDays().endtime, // 结束日期
        sparePartsReturnNo: '', // 采购退货单号
        returnReason: '', // 退货原因
        warehouseSn: undefined, // 出库仓库
        product: {
          name: '', // 产品名称
          code: '', // 产品编码
          brandType: undefined, // 品牌分类
          productBrandSn: undefined// 产品品牌 sn
        },
        supplier: {
          supplierSn: '', // 供应商sn
          supplierName: '', // 供应商名称
          provinceSn: undefined, // 省
          citySn: undefined, // 市
          districtSn: undefined// 区
        }
      },
      rules: {
        'time': [{ required: true, message: '请选择退货完成日期', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        delete params.time
        // 获取列表数据 有分页
        return sparePartsReturnDetailReportList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 统计
            this.getCount(params)
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      totalData: null
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '采购退货单号', dataIndex: 'sparePartsReturnNo', width: 90, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '出库仓库', dataIndex: 'warehouseName', width: 150, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '省份', dataIndex: 'supplier.provinceName', width: 80, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '供应商名称', dataIndex: 'supplier.supplierName', width: 120, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '退货原因', dataIndex: 'returnReasonDictValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '补充说明', dataIndex: 'explainInfo', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '附件', width: 100, align: 'center', scopedSlots: { customRender: 'attachmentList' } },
        { title: '退货完成日期', dataIndex: 'auditDate', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '入库单号', dataIndex: 'sparePartsNo', width: 90, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'product.productBrandName', width: 110, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '二级分类', dataIndex: 'product.productTypeName2', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '三级分类', dataIndex: 'product.productTypeName3', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productCode', width: 80, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'product.name', width: 150, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'product.unit', width: 50, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '批次号', dataIndex: 'stockBatchNo', width: 90, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '入库数量', dataIndex: 'putQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '已退数量', dataIndex: 'returnedQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '申请退货数量', dataIndex: 'qty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作员', dataIndex: 'submitorName', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]

      if (_this.$hasPermissions('M_urchaseDetailReturnList_costPrice')) {
        arr.splice(16, 0, { title: '入库单价', dataIndex: 'cost', width: 60, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
        arr.splice(20, 0, { title: '退货金额', dataIndex: 'totalCost', width: 60, align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } })
      }
      return arr
    }
  },
  watch: {
    // 展开关闭
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    // 总计
    getCount (params) {
      sparePartsReturnDetailReportStat(params).then(res => {
        if (res.status == 200 && res.data) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 供应商 change
    getSupplierName (val, item) {
      this.queryParam.supplier.supplierName = item.supplierName
      this.queryParam.supplier.supplierSn = val
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (!_this.queryParam.supplier.supplierSn) {
            _this.queryParam.supplier.supplierName = undefined
          }
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择退货完成日期')
          return false
        }
      })
    },
    //  退货完成日期  change
    dateChange (date) {
      if (date[0] && date[1]) {
        this.queryParam.time = date
      } else {
        this.queryParam.time = []
      }
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    //  重置
    resetSearchForm () {
      this.queryParam.time = [
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ]
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.queryParam.beginDate = getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = getDate.getCurrMonthDays().endtime
      this.queryParam.sparePartsReturnNo = ''
      this.queryParam.product.code = ''
      this.queryParam.product.name = ''
      this.queryParam.supplier.supplierSn = ''
      this.queryParam.supplier.supplierName = ''
      this.queryParam.returnReason = undefined
      this.queryParam.product.productBrandTypeSn = undefined
      this.queryParam.product.productBrandSn = undefined
      this.queryParam.supplier.provinceSn = undefined
      this.queryParam.supplier.citySn = undefined
      this.queryParam.supplier.districtSn = undefined
      this.queryParam.warehouseSn = undefined
      this.totalData = null
      if (this.advanced) {
        this.$refs.areaList.clearData()
      }
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const params = _this.queryParam
          _this.showExport = true
          _this.exportLoading = true
          _this.spinning = true
          _this.$store.state.app.curActionPermission = 'B_urchaseDetailReturn_export'
          hdExportExcel(sparePartsReturnReportExportDetail, params, '采购退货明细报表', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 地区
    areaChange (val) {
      this.queryParam.supplier.provinceSn = val[0] ? val[0] : ''
      this.queryParam.supplier.citySn = val[1] ? val[1] : ''
      this.queryParam.supplier.districtSn = val[2] ? val[2] : ''
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 215
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.resetSearchForm()
      this.setTableH()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.resetSearchForm()
      this.setTableH()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
