<template>
  <a-card :bordered="false" class="inventoryWarningList-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="产品编码">
              <a-input id="inventoryWarningList-orderBundleNo" v-model.trim="queryParam.orderBundleNo" allowClear placeholder="请输入产品编码"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="原厂编码">
              <a-input id="inventoryWarningList-custMobile" v-model.trim="queryParam.orderBundle.custMobile" allowClear placeholder="请输入原厂编码"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="产品名称">
              <a-input id="inventoryWarningList-bundleName" v-model.trim="queryParam.bundleName" allowClear placeholder="请输入产品名称"/>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-item label="产品品牌">
                <a-select id="inventoryWarningList-bundleNames" placeholder="请选择产品品牌" allowClear v-model="queryParam.brand">
                  <a-select-option v-for="item in brandData" :key="item.stationNo" :value="item.stationNo">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="产品类别">
                <a-cascader :options="typeData" placeholder="请选择产品类别" allowClear v-model="queryParam.brand" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="预警提示">
                <a-select id="inventoryWarningList-bundleNames" placeholder="请选择预警提示" allowClear v-model="queryParam.brand">
                  <a-select-option v-for="item in brandData" :key="item.stationNo" :value="item.stationNo">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="24">
            <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryWarningList-refresh">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="inventoryWarningList-reset">重置</a-button>
            <a-button style="margin-left: 8px" type="danger" @click="handleExport" :disabled="disabled" :loading="exportLoading" id="inventoryWarningList-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="inventoryWarningList-update" type="primary" @click="handleupdate">批量更新</a-button>
    </div>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      bordered>
      <!-- 需要编辑的字段 -->
      <template
        v-for="col in ['onWayNum', 'maxInventory', 'minInventory']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <a-input
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            @change="e => handleChange(e.target.value, record.key, col)"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <div class="editable-row-operations">
          <span v-if="record.editable">
            <a @click="() => save(record.key)">保存</a>
            <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
              <a>取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a :disabled="editingKey !== ''" @click="() => edit(record.key)">编辑</a>
          </span>
        </div>
      </template>
    </s-table>
  </a-card>
</template>

<script>
import moment from 'moment'
// import { customerBundleDelayList, customerBundleExportDelay } from '@/api/FinancialManagement'
import { STable } from '@/components'
export default {
  components: { STable },
  data () {
    return {
      advanced: false,  // 高级搜索 展开/关闭
      queryParam: { //  查询条件
        orderBundleNo: '', //  订单编号
        orderBundle: {
          custMobile: '' //  客户手机
        },
        bundleName: '', //  套餐名称
        itemName: '', //  服务名称
        brand: undefined,  //  产品品牌
        inventoryNum: false  //  库存数量是否为0
      },
      exportLoading: false, // 导出loading
      disabled: false, //  查询、重置按钮是否可操作
      brandData: [],  //  产品品牌下拉数据
      typeData: [],  //  产品类别下拉数据
      columns: [
        { title: '序号', dataIndex: 'no', width: 70, align: 'center' },
        { title: '产品编码', dataIndex: 'productNum', width: 160, align: 'center' },
        { title: '产品名称', dataIndex: 'productName', width: 200, align: 'center', ellipsis: true },
        { title: '级别', dataIndex: 'productNasme', width: 100, align: 'center' },
        { title: '原厂编码', dataIndex: 'productOldNum', width: 160, align: 'center' },
        { title: '产品品牌', dataIndex: 'productBrand', width: 200, align: 'center' },
        { title: '产品分类', dataIndex: 'productType', width: 200, align: 'center' },
        { title: '实时库存数（个）', dataIndex: 'inventoryNumy', width: 180, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '在途数（个）', scopedSlots: { customRender: 'onWayNum' }, width: 180, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '总库存数（个）', dataIndex: 'inventoryNumw', width: 180, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '最大库存数（个）', scopedSlots: { customRender: 'maxInventory' }, width: 180, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '最小库存数（个）', scopedSlots: { customRender: 'minInventory' }, width: 180, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '差异数量', dataIndex: 'inventoryNumh', width: 180, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '预警提示', dataIndex: 'inventoryNum', width: 180, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 240, align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        // return customerBundleDelayList( 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
        // })
        const _this = this
        return new Promise(function(resolve, reject){
          const data = {
            pageNo: 1,
            pageSize: 10,
            list: [
              { id: '1', productNum: 'jgqp11111111111', productName: '产品1', productOldNum: 'jgqp111123545', productBrand: '箭冠品牌', productType: '产品分类1', inventoryNum: '5', inventoryMoney: '122' }
            ]
          }
          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
          resolve(data)
        })
      },
      openModal: false,  //  查看库存详情  弹框
      itemId: '',  //  当前库存记录id
      editingKey: ''
    }
  },
  methods: {
    //  重置
    resetSearchForm () {
      this.queryParam.orderBundleNo = ''
      this.queryParam.orderBundle.custMobile = ''
      this.queryParam.bundleName = ''
      this.queryParam.itemName = ''
      this.oldTime = undefined
      this.newTime = undefined
      this.$refs.table.refresh(true)
    },
    //  批量更新
    handleupdate(){
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确定提交批量更新的内容吗？',
        okText: '确定',
        cancelText: '取消',
        onOk () {
          // delectRolePower({
          //   id: row.id
          // }).then(res => {
          //   console.log(res, 'res1111')
          //   if (res.status == 200) {
          //     _this.$message.success(res.message)
          //     _this.$refs.table.refresh()
          //   }
          // })
        }
      })
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    save(key) {
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.filter(item => key === item.key)[0];
      const targetCache = newCacheData.filter(item => key === item.key)[0];
      if (target && targetCache) {
        delete target.editable;
        this.data = newData;
        Object.assign(targetCache, target);
        this.cacheData = newCacheData;
      }
      this.editingKey = '';
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.key)[0]);
        delete target.editable;
        this.data = newData;
      }
    },
    //  导出
    handleExport () {
      const params = this.queryParam
      this.exportLoading = true
      customerBundleExportDelay(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()
    }
  }
}
</script>

<style lang="less">
  .inventoryWarningList-wrap{
    .sTable{
      table{
        width: auto;
      }
    }
  }
</style>