<template>
  <a-card :bordered="false" v-if="visible">
    <a-row :gutter="48" slot="extra">
      <a-col :md="48" :sm="48">
        <span class="table-page-search-submitButtons" style="float: right" >
          <!--          <a-button style="margin-left: 8px" type="primary" @click="updateList()">保存</a-button>-->
          <a-button style="margin-left: 8px" @click="handleCancel()">返回列表</a-button>
        </span>
      </a-col>
    </a-row>
    <div class="table-page-search-wrapper" @keyup.enter="handleEnter">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="关键字">
              <a-input v-model="queryParam.keyword" placeholder="请输入名称/类型名称"/>
            </a-form-item>
          </a-col>
          <a-col :md="8 || 24" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="handleOk">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button style="margin-left: 8px" v-if="$auth('purchase-purchase-demand-plan-lists-add')" type="primary" icon="plus" @click="updateList">列表保存</a-button>
    </div>

    <a-table
      ref="table"
      size="small"
      rowKey="id"
      :columns="columns"
      :loading="loading"
      :scroll="{x: 1, y: BaseTool.Constant.scrollY }"
      :data-source="dataSource"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template slot="quantity" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input type="number" :value="text" :id="record.id + ',quantity'" @change="$event => onQuantityChange($event, record.id, 'quantity')" />
        </div>
      </template>

      <!--      <span slot="action" slot-scope="record">-->
      <!--        <template>-->
      <!--          &lt;!&ndash;          <a @click="handleView(record)">查看</a>&ndash;&gt;-->
      <!--          &lt;!&ndash;          <operation-button&ndash;&gt;-->
      <!--          &lt;!&ndash;            v-if="$auth('purchase-purchase-plan-lists-edit')"&ndash;&gt;-->
      <!--          &lt;!&ndash;            @click="handleEdit(record)"&ndash;&gt;-->
      <!--          &lt;!&ndash;          >修改</operation-button>&ndash;&gt;-->
      <!--          <operation-button-->
      <!--            :show-divider="false"-->
      <!--            v-if="$auth('purchase-purchase-plan-lists-del')"-->
      <!--            :type="2"-->
      <!--            title="是否要删除该条数据？"-->
      <!--            @confirm="batchDelete(record.id)">删除</operation-button>-->
      <!--        </template>-->
      <!--      </span>-->
    </a-table>
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { updatePurchaseDemandPlanListForPlan, getPurchaseDemandPlanListPage } from '@/api/purchase/purchase-demand-plan-list'
export default {
  name: 'PurchaseDemandPlanListForQuantity',
  components: {
    STable,
    Ellipsis
  },
  data () {
    return {
      // 查询参数
      queryParam: {
      },
      visible: false,
      purchaseDemandPlanId: '-1',
      showSizeChanger: false,
      addFlag: null,
      loading: false,
      isCreated: false,
      pagination: {
        current: 1,
        pageSize: 10
      },
      columns: [],
      // 表头
      columnItems: [
        {
          title: '序号',
          dataIndex: 'index',
          checked: true,
          width: 70,
          customRender: (text, record, index) => {
            return `${(this.pagination.current - 1) * this.pagination.pageSize + index + 1}`
          }
        },
        {
          title: '编号',
          dataIndex: 'no',
          checked: true,
          width: 200
        },
        {
          title: '名称',
          dataIndex: 'name',
          checked: true,
          width: 150
        },
        {
          title: '规格',
          dataIndex: 'specs',
          checked: true,
          width: 100
        },
        {
          title: '单价',
          dataIndex: 'price',
          checked: true,
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          checked: true,
          width: 150,
          scopedSlots: { customRender: 'quantity' }
        },
        {
          title: '总价',
          dataIndex: 'totalMoney',
          checked: true,
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          checked: true,
          width: 120
        },
        {
          title: '单位',
          dataIndex: 'unit',
          checked: true,
          width: 90
        },
        {
          title: '适用车型',
          dataIndex: 'suitableModel',
          width: 120
        },
        // {
        //   title: '车架号',
        //   dataIndex: 'vin',
        //   width: 150
        // },
        // {
        //   title: '发动机号',
        //   dataIndex: 'engineNum',
        //   width: 150
        // },

        {
          title: '已到数量',
          dataIndex: 'arrivedQuantity',
          width: 90,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '产地',
          dataIndex: 'producePlace',
          width: 90,
          checked: true,
          customRender: (text, record, index) => {
            return this.BaseTool.Table.getMapText(this.areaMap, text)
          }
        },
        {
          title: '重量',
          dataIndex: 'weight',
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '体积',
          dataIndex: 'volume',
          width: 90,
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '外形尺寸',
          dataIndex: 'dimension',
          width: 90
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: 90
        },
        {
          title: '创建人名称',
          dataIndex: 'createdUserName',
          width: 120
        },
        {
          title: '创建时间',
          dataIndex: 'createdTime',
          width: 120
        }
      ],
      // 下拉框map
      unitMap: {},
      areaMap: {},
      dataSource: [],
      // 加载数据方法 必须为 Promise 对象
      selectedRowKeys: [],
      selectedRows: [],

      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  props: {
    viewFlag: {
      type: Boolean,
      default: false
    }
  },
  created () {
    // 下拉框map
    this.unitMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SBINFO_UNIT)
    this.areaMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PRODUCER_AREA)
    if (!this.viewFlag) {
      this.columns = [
        ...this.columnItems,
        {
          title: '操作',
          key: 'action',
          width: '200px',
          fixed: 'right',
          checked: true,
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ]
      this.optionAlertShow = true
    } else {
      this.columns = [
        ...this.columnItems
      ]
      this.optionAlertShow = false
    }
    this.tableOption()
  },
  methods: {
    base (purchaseDemandPlanId) {
      this.pagination = {
        current: 1,
        pageSize: 10
      }
      this.visible = true
      this.purchaseDemandPlanId = purchaseDemandPlanId
      if (this.isCreated) {
        this.handleOk()
      } else {
        this.handleOk()
        this.tableOption()
        this.isCreated = true
      }
      this.visible = true
    },
    handleTableChange (pagination, filters, sorter) {
      console.log(pagination)
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.loading = true
      this.updateList()
    },
    updateList (func) {
      updatePurchaseDemandPlanListForPlan(this.purchaseDemandPlanId, this.dataSource).then(res => {
        this.handleOk()
        func && func()
      })
    },
    onQuantityChange (e, id, attr) {
      const value = parseFloat(e.target.value)
      if (value !== 0 && !value) {
        return
      }
      const dataSource = [...this.dataSource]
      const target = dataSource.find(item => item.id === id)
      if (target) {
        target[attr] = value
        target['totalMoney'] = Math.floor(value * target['price'] * 10000) / 10000
        this.dataSource = dataSource
      }
    },
    initData () {
      this.loading = true
      const parameter = {
        ...this.queryParam,
        demandPlanId: this.purchaseDemandPlanId,
        dataScope: {
          sortBy: 'asc',
          sortName: 'no'
        },
        pageNum: this.pagination.current,
        pageSize: this.pagination.pageSize
      }
      return getPurchaseDemandPlanListPage(parameter)
        .then(res => {
          const data = res.data
          // data.rows = this.BaseTool.ListForm.getOneListHandledRowsForEdit(this, data.rows, 'goodsId')
          // this.$store.dispatch('setOneListUpdate', data.rows)
          this.$store.dispatch('setCheckedRows', [])
          this.dataSource = data.rows
          const pagination = { ...this.pagination }
          pagination.total = data.total
          this.pagination = pagination
          this.loading = false
        })
    },
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: false,
                name: record.id
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleOk () {
      // this.pagination.current = 1
      this.initData()
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm () {
      this.queryParam = {
        purchasePlanId: this.purchasePlanId
      }
      this.handleOk()
    },
    handleCancel (values) {
      this.visible = false
      const that = this
      this.updateList(function () {
        that.$emit('ok', values)
      })
    },
    handleEnter () {
      this.handleOk()
    }
  }
}
</script>
