<template>
  <a-card size="small" :bordered="false" class="allocateBillList-wrap">
    <!-- 搜索条件 -->
    <div 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 ref="rangeDate" @change="dateChange" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="调往对象">
              <a-input id="allocateBillList-targetName" v-model.trim="queryParam.targetName" allowClear placeholder="请输入调往对象"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="调拨类型">
              <a-select id="allocateBillList-allocateTypeSn" v-model="queryParam.allocateTypeSn" placeholder="请选择调拨类型" allowClear >
                <a-select-option v-for="item in allocateTypeList" :key="item.allocateTypeSn" :value="item.allocateTypeSn">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-item label="业务状态">
                <v-select
                  v-model="queryParam.state"
                  ref="state"
                  id="allocateBillList-state"
                  code="ALLOCATE_STATUS"
                  placeholder="请选择业务状态"
                  allowClear
                ></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="调拨单号">
                <a-input id="allocateBillList-allocateNo" v-model.trim="queryParam.allocateNo" allowClear placeholder="请输入调拨单号"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="allocateBillList-refresh">查询</a-button>
            <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="allocateBillList-reset">重置</a-button>
            <!-- <a-button
              style="margin: 0 0 18px 5px"
              type="primary"
              class="button-warning"
              @click="handleExport"
              :disabled="disabled"
              :loading="exportLoading"
              id="allocateBillList-export">导出</a-button> -->
            <a @click="advanced=!advanced" style="margin-left: 8px">
              {{ advanced ? '收起' : '展开' }}
              <a-icon :type="advanced ? 'up' : 'down'"/>
            </a>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮 -->
    <div class="table-operator">
      <a-button id="allocateBillList-add" type="primary" class="button-error" @click="openModal=true">新增</a-button>
    </div>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :scroll="{ x: 1940, y: tableHeight }"
      bordered>
      <!-- 单号 -->
      <template slot="allocateNo" slot-scope="text, record">
        <span style="color: #ed1c24;cursor: pointer;" @click="handleDetail(record)">{{ record.allocateNo }}</span>
      </template>
      <!-- 财务状态 -->
      <template slot="settleState" slot-scope="text, record">
        <a-badge :color="text=='FINISH'?'#87d068':'gold'" :text="record.settleStateDictValue" />
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          type="link"
          v-if="record.state == 'WAIT_AUDIT'"
          class="button-warning"
          @click="handleExamine(record)"
          id="allocateBillList-examine-btn">审核</a-button>
        <a-button
          size="small"
          type="link"
          v-if="(record.state == 'WAIT_SUBMIT') || (record.state == 'WAIT_AUDIT') || (record.state == 'AUDIT_REJECT')"
          class="button-info"
          @click="handleEdit(record)"
          id="allocateBillList-edit-btn">编辑</a-button>
        <a-button
          size="small"
          type="link"
          v-if="(record.state == 'WAIT_SUBMIT') || (record.state == 'WAIT_AUDIT') || (record.state == 'AUDIT_REJECT')"
          class="button-error"
          @click="handleDel(record)"
          id="allocateBillList-del-btn">删除</a-button>
        <span v-if="(record.state != 'WAIT_SUBMIT') && (record.state != 'WAIT_AUDIT') && (record.state != 'AUDIT_REJECT')">--</span>
      </template>
    </s-table>
    <!-- 新增 -->
    <basic-info-modal :openModal="openModal" @ok="handleOk" @close="openModal=false" />
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, VSelect } from '@/components'
import basicInfoModal from './basicInfoModal.vue'
import rangeDate from '@/views/common/rangeDate.vue'
import { allocateBillList, allocateBillDel, allocateBillAudit, allocateBillExport } from '@/api/allocateBill'
import { allocateTypeAllList } from '@/api/allocateType'
export default {
  components: { STable, VSelect, basicInfoModal, rangeDate },
  data () {
    return {
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        beginDate: '',
        endDate: '',
        targetName: '', //  调往对象
        allocateTypeSn: undefined, //  调拨类型
        state: undefined, //  业务状态
        allocateNo: '' //  调拨单号
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: 160, align: 'center' },
        { title: '调拨单号', scopedSlots: { customRender: 'allocateNo' }, align: 'center' },
        { title: '调往对象', dataIndex: 'targetName', width: 220, align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户类型', dataIndex: 'dealerLevelDictValue', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '总数量', dataIndex: 'totalQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总成本', dataIndex: 'totalCost', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总售价', dataIndex: 'totalPrice', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '审核时间', dataIndex: 'auditTime', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调拨类型', dataIndex: 'allocateTypeName', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '业务状态', dataIndex: 'stateDictValue', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '打印状态', dataIndex: 'printStateDictValue', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '打印次数', dataIndex: 'printCount', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 180, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        if (this.tableHeight == 0) {
          this.tableHeight = window.innerHeight - 380
        }
        return allocateBillList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
        })
      },
      allocateTypeList: [], //  调拨类型
      openModal: false //  新增编辑  弹框
    }
  },
  methods: {
    //  创建时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeDate.resetDate()
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.targetName = ''
      this.queryParam.allocateTypeSn = undefined
      this.queryParam.state = undefined
      this.queryParam.allocateNo = ''
      this.$refs.table.refresh(true)
    },
    //  基本信息  保存
    handleOk (data) {
      this.$router.push({ path: `/allocationManagement/transferOut/add/${data.allocateSn}/${data.targetName}` })
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          allocateBillDel({ sn: row.allocateSn }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
          })
        }
      })
    },
    //  审核
    handleExamine (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要审核通过吗？',
        centered: true,
        closable: true,
        okText: '审核通过',
        cancelText: '审核不通过',
        onOk () {
          _this.auditOrder(row.allocateSn, 'WAIT_OUT_WAREHOUSE')
        },
        onCancel (e) {
          if (!e.triggerCancel) {
            _this.auditOrder(row.allocateSn, 'AUDIT_REJECT')
          }
          _this.$destroyAll()
        }
      })
    },
    // 审核
    auditOrder (sn, state) {
      const _this = this
      allocateBillAudit({ sn: sn, state: state }).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
        }
      })
    },
    //  详情
    handleDetail (row) {
      this.$router.push({ path: `/allocationManagement/transferOut/detail/${row.allocateSn}` })
    },
    //  编辑
    handleEdit (row) {
      this.$router.push({ path: `/allocationManagement/transferOut/edit/${row.allocateSn}/${row.targetName}/${row.dealerLevel}` })
    },
    //  导出
    handleExport () {
      const params = this.queryParam
      this.exportLoading = true
      allocateBillExport(params).then(res => {
        this.exportLoading = false
        this.download(res)
      })
    },
    download (data) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDHHmmss')
      const fname = '调拨列表' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    },
    //  调拨类型
    getAllocateTypeAllList () {
      allocateTypeAllList().then(res => {
        if (res.status == 200) {
          this.allocateTypeList = res.data
        } else {
          this.allocateTypeList = []
        }
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.openModal = false
      vm.getAllocateTypeAllList()
    })
  }
}
</script>
