<template>
  <a-card size="small" :bordered="false" class="purchaseOrderList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <rangeDate id="purchaseOrderList-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="purchaseOrderList-purchaseBillNo" v-model.trim="queryParam.purchaseBillNo" allowClear placeholder="请输入采购单号"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="供应商">
                <a-select
                  id="purchaseOrderList-purchaseTargetSn"
                  placeholder="请选择供应商"
                  allowClear
                  v-model="queryParam.purchaseTargetSn"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  @change="tragetTypeChange">
                  <a-select-option v-for="item in supplierList" :pyCode="item.pyCode" :id="'purchaseOrderList-purchaseTargetSn-'+item.purchaseTargetSn" :key="item.purchaseTargetSn" :value="item.purchaseTargetSn">
                    {{ item.purchaseTargetName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="advanced">
              <a-form-item label="业务状态">
                <a-select id="purchaseOrderList-billStatus" allowClear v-model="queryParam.billStatus" placeholder="请选择业务状态">
                  <a-select-option id="purchaseOrderList-billStatus-all" value="">全部</a-select-option>
                  <a-select-option id="purchaseOrderList-billStatus-wait" value="WAIT_SUBMIT">待提交</a-select-option>
                  <a-select-option id="purchaseOrderList-billStatus-submit" value="SUBMIT">已提交</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="advanced">
              <a-form-item label="财务状态">
                <v-select
                  style="width: 100%;"
                  v-model="queryParam.financialStatus"
                  ref="financialStatus"
                  id="purchaseOrderList-financialStatus"
                  code="FINANCIAL_PAY_STATUS"
                  placeholder="请选择财务状态"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="advanced">
              <a-form-item label="单据来源">
                <v-select
                  style="width: 100%;"
                  v-model="queryParam.purchaseBillSource"
                  ref="purchaseBillSource"
                  id="purchaseOrderList-purchaseBillSource"
                  code="PURCHASE_SOURCE"
                  placeholder="请选择单据来源"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" v-show="advanced">
              <a-form-item label="促销单">
                <v-select
                  v-model="queryParam.promotionFlag"
                  ref="promotionFlag"
                  id="purchaseOrderList-promotionFlag"
                  code="FLAG"
                  placeholder="请选择是否促销单"
                  allowClear></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="purchaseOrderList-refresh">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm()" :disabled="disabled" id="purchaseOrderList-reset">重置</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px" id="purchaseOrderList-advanced">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator" style="display:flex;align-items: center;justify-content: space-between;">
        <div>
          <a-button id="purchaseOrderList-add" type="primary" v-if="$hasPermissions('B_purchaseNew')&&($hasPermissions('B_SUPPLIER_SJ')||$hasPermissions('B_SUPPLIER_ZB'))" class="button-error" @click="handleAdd">新增</a-button>
        </div>
        <div>
          <a-dropdown v-model="showCell">
            <a-button type="link" class="button-default" id="purchaseOrderList-showCell"> <a-icon type="setting" />  显示</a-button>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-checkbox v-model="showOrderType" id="purchaseOrderList-orderType">订单类型</a-checkbox>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </div>
      </div>
      <!-- alert -->
      <a-alert type="info" style="margin-bottom:10px">
        <div slot="message">
          共 <strong>{{ totalData&&(totalData.totalRecord || totalData.totalRecord==0) ? totalData.totalRecord : '--' }}</strong> 条记录，
          采购数量合计 <strong>{{ totalData&&(totalData.totalQty || totalData.totalQty==0) ? totalData.totalQty : '--' }}</strong> ，
          采购金额合计 <strong>{{ totalData&&(totalData.totalAmount || totalData.totalAmount==0) ? toThousands(totalData.totalAmount,2) : '--' }}</strong>，
          审核金额合计 <strong>{{ totalData&&(totalData.totalAuthAmount || totalData.totalAuthAmount==0) ? toThousands(totalData.totalAuthAmount,2) : '--' }}</strong>
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+84.5+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 采购单号 -->
        <template slot="purchaseBillNo" slot-scope="text, record">
          <span class="table-td-link" :id="'purchaseOrderList-detail-'+record.id" v-if="$hasPermissions('B_purchaseDetail')" @click="handleDetail(record)">{{ record.purchaseBillNo }}</span>
          <span v-else>{{ record.purchaseBillNo }}</span>
          <a-badge v-if="record.promotionFlag && record.promotionFlag==1" count="促" :number-style="{ backgroundColor: '#52c41a', zoom:'80%',marginLeft:'5px' }"></a-badge>
          <a-badge count="改" v-if="record.billStatus=='HQ_CHANGE'||record.billStatus=='SUPERIOR_CHANGE'" :number-style="{ zoom:'80%',marginLeft:'5px' }"></a-badge>
          <!-- <a-badge count="转促" v-if="record.borrowedShowFlag=='1'" :number-style="{ zoom:'80%',marginLeft:'5px',backgroundColor: '#BfBf00' }"></a-badge> -->
        </template>
        <!-- 审核icon -->
        <template slot="audit" slot-scope="text, record">
          <stateIcon :title="record.billStatusDictValue" v-if="record.billStatus!='AUDIT_REJECT'" :state="record.billStatus == 'WAIT_PUT_WAREHOUSE'||record.billStatus=='AUDIT_PASS'||record.billStatus == 'FINISH'?'1':'2'"></stateIcon>
          <stateIcon :title="record.billStatusDictValue" v-else :state="0"></stateIcon>
        </template>
        <!-- 付款icon -->
        <template slot="financial" slot-scope="text, record">
          <stateIcon :title="record.financialStatusDictValue" :state="record.financialStatus == 'FINISH'?'1':'2'"></stateIcon>
        </template>
        <!-- 入库icon -->
        <template slot="waitOut" slot-scope="text, record">
          <stateIcon :state="record.billStatus == 'FINISH'?'1':'2'"></stateIcon>
        </template>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            type="link"
            class="button-primary"
            :id="'purchaseOrderList-edit-'+record.id"
            v-if="(record.billStatus == 'WAIT_SUBMIT'||record.billStatus == 'AUDIT_REJECT') && $hasPermissions('B_purchaseEdit')"
            @click="handleEdit(record)"
          >编辑</a-button>
          <a-button
            size="small"
            type="link"
            class="button-error"
            :id="'purchaseOrderList-del-'+record.id"
            v-if="(record.billStatus == 'WAIT_SUBMIT'||record.billStatus == 'AUDIT_REJECT'||record.billStatus == 'CANCEL') &&$hasPermissions('B_purchaseDel')"
            @click="handleDel(record)"
          >删除</a-button>
          <span v-if="!((record.billStatus == 'WAIT_SUBMIT'||record.billStatus == 'AUDIT_REJECT'||record.billStatus == 'CANCEL') && $hasPermissions('B_purchaseEdit')) && !((record.billStatus == 'WAIT_SUBMIT'||record.billStatus == 'AUDIT_REJECT') &&$hasPermissions('B_purchaseDel'))">--</span>
        </template>
      </s-table>
    </a-spin>
    <!-- 选择基本信息弹框 -->
    <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import getDate from '@/libs/getDate.js'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import basicInfoModal from './basicInfoModal.vue'
import stateIcon from '@/views/common/stateIcon'
// 接口
import { purchaseList, purchaseDel, purchaseCount } from '@/api/purchase'
import { queryReturnSupplierList } from '@/api/purchaseReturn'
export default {
  name: 'PurchaseList',
  components: { STable, VSelect, basicInfoModal, rangeDate, stateIcon },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, //  高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      openModal: false, // 基本信息弹框是否显示
      supplierList: [], // 供应商列表
      tableHeight: 0, // 表格高度
      time: [ // 时间
        getDate.getCurrMonthDays().starttime,
        getDate.getCurrMonthDays().endtime
      ],
      // 查询参数
      queryParam: {
        purchaseBillNo: '', // 采购单号
        purchaseTargetSn: undefined, // 供应商sn
        purchaseTargetType: undefined, // 采购方类型
        billStatus: undefined, // 单据状态
        financialStatus: undefined, // 财务状态
        purchaseBillSource: undefined, // 单据来源
        promotionFlag: undefined, // 是否促销商品
        beginDate: getDate.getCurrMonthDays().starttime, // 开始时间
        endDate: getDate.getCurrMonthDays().endtime// 结束时间
      },
      totalData: { // 统计数据
        totalRecord: 0, // 总条数
        totalCategory: 0, // 总款数
        totalQty: 0, // 总数量
        totalAmount: 0// 总金额
      },
      showCell: false, // 是否显示自定义列
      showOrderType: false, // 是否显示订单类型
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        if (!params.billStatus) {
          params.billStatus = undefined
        }
        // 获取统计数据
        this.getTotalData(params)
        return purchaseList(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
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  computed: {
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '采购单号', scopedSlots: { customRender: 'purchaseBillNo' }, width: '13%', align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '供应商', dataIndex: 'purchaseTargetName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品款数', dataIndex: 'totalCategory', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购数量', dataIndex: 'totalQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '采购金额', dataIndex: 'discountedAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '审核数量', dataIndex: 'totalPushedQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核金额', dataIndex: 'totalPushedAmount', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text, 2) : '--') } },
        { title: '已取消数量', dataIndex: 'totalCancelQty', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '采购状态', dataIndex: 'billStatusDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '审核', scopedSlots: { customRender: 'audit' }, width: '3%', align: 'center' },
        { title: '入库', scopedSlots: { customRender: 'waitOut' }, width: '3%', align: 'center' },
        { title: '付款', scopedSlots: { customRender: 'financial' }, width: '3%', align: 'center' },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '9%', align: 'center' }
      ]
      if (this.showOrderType) {
        arr.splice(4, 0, { title: '订单类型', dataIndex: 'orderTypeDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      return arr
    }
  },
  methods: {
    // 统计信息
    getTotalData (params) {
      purchaseCount(params).then(res => {
        this.totalData = res.data || null
      })
    },
    // 供应商change
    tragetTypeChange (val) {
      const ind = this.supplierList.findIndex(item => item.purchaseTargetSn == val)
      if (ind != -1) {
        this.queryParam.purchaseTargetType = this.supplierList[ind].purchaseTargetType
      } else {
        this.queryParam.purchaseTargetSn = undefined
        this.queryParam.purchaseTargetType = undefined
      }
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  新增
    handleAdd () {
      this.openModal = true
    },
    //  基本信息  保存
    handleOk (row) {
      this.$router.push({ name: `purchaseOrderAdd`, params: { sn: row.purchaseBillSn, dealerSn: (row.purchaseTargetType == 'DEALER_UP' ? row.purchaseTargetSn : 'NONE') } })
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ name: `purchaseOrderEdit`, params: { sn: row.purchaseBillSn, dealerSn: (row.purchaseTargetType == 'DEALER_UP' ? row.purchaseTargetSn : 'NONE') } })
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ name: `purchaseOrderDetail`, params: { sn: row.purchaseBillSn } })
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          purchaseDel({
            id: row.id
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    //  重置
    resetSearchForm (flag) {
      this.$refs.rangeDate.resetDate(flag ? '' : this.time)
      this.queryParam.beginDate = flag ? '' : getDate.getCurrMonthDays().starttime
      this.queryParam.endDate = flag ? '' : getDate.getCurrMonthDays().endtime
      this.queryParam.orderBundleNo = ''
      this.queryParam.purchaseBillNo = ''
      this.queryParam.purchaseTargetSn = undefined
      this.queryParam.purchaseTargetType = undefined
      this.queryParam.billStatus = undefined
      this.queryParam.financialStatus = undefined
      this.queryParam.purchaseBillSource = undefined
      this.queryParam.promotionFlag = undefined
      if (!flag) {
        this.$refs.table.refresh(true)
        this.setIsHomeNav(this.$route.name, null)
      }
    },
    // 供应商筛选
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取供应商数据
    getSupperList () {
      queryReturnSupplierList({}).then(res => {
        if (res.status == 200) {
          this.supplierList = res.data
        } else {
          this.supplierList = []
        }
      })
    },
    // 页面初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      this.openModal = false
      this.getSupperList()

      // 是否打开的页签
      const a = this.$store.state.app.isNewTab
      // 是否要刷新列表
      const b = this.$store.state.app.updateList
      // 是否从首页点击进入
      const isHomeNav = this.getIsHomeNav()[this.$route.name]

      // 从首页进入,判断式新建还式待办查询
      if (isHomeNav) {
        // 新增
        if (isHomeNav.type == 'new') {
          this.resetSearchForm()
          this.openModal = true
        }
        // 待办
        if (isHomeNav.type == 'todo') {
          this.resetSearchForm(true)
          this.$refs.rangeDate.resetDate([isHomeNav.pageParams.beginDate, isHomeNav.pageParams.endDate])
          this.queryParam = Object.assign(this.queryParam, isHomeNav.pageParams)
          this.$refs.table.refresh(true)
        }
      } else {
        // 如果是新页签打开，则重置当前页面
        if (a && !b) {
          this.resetSearchForm()
        }
        // 仅刷新列表，不重置页面
        if (b || a == b) {
          this.$refs.table.refresh()
        }
      }
    },
    // 表格高度计算
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 275
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
    })
  }
}
</script>
