<template>
  <a-modal
    :title="modalTitle"
    :width="950"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">

      <a-form-item v-show="false" >
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>

      <a-form-item
        label="单号"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          v-decorator="['no', {rules: [{required: false, message: '单号不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="类型"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select disabled @change="handleTypeChange" v-decorator="['type', {rules: [{required: true, message: '类型不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in typeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="物品类型"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-select disabled v-decorator="['goodType', {rules: [{required: true, message: '物品类型不能为空'}]}]" placeholder="请选择">
          <a-select-option
            v-for="(label,value) in goodTypeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="采购单Id"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          style="width:70%;margin-right:5px"
          v-decorator="['purchaseId']" />
        <a-button type="primary" @click="handlePurchaseOrderSelect">查看明细</a-button>
      </a-form-item>
      <a-form-item
        label="发运单Id"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          style="width:70%;margin-right:5px"
          v-decorator="['purchaseDispatchOrderId']" />
        <a-button type="primary" @click="handlePurchaseDispatchOrderSelect">查看明细</a-button>
      </a-form-item>
      <a-form-item
        label="仓库id"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
        v-show="false"
      >
        <a-input
          v-decorator="['storeId', {rules: [{required: true, message: '仓库id不能为空'}]}]" />
      </a-form-item>
      <a-form-item
        label="仓库"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-input
          disabled
          style="width:70%;margin-right:5px"
          v-decorator="['storeName', {rules: [{required: true, message: '仓库名称不能为空'}]}]" />
        <a-button type="primary" @click="handleStoreSelect">查看仓库</a-button>
      </a-form-item>
      <a-form-item
        label="备注"
        :labelCol="BaseTool.Constant.labelCol"
        :wrapperCol="BaseTool.Constant.wrapperCol"
      >
        <a-textarea
          :rows="4"
          v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]"/>
      </a-form-item>
    </a-form>

    <a-tabs type="card" default-active-key="1">
      <a-tab-pane key="1" tab="详情">
        <div class="table-operator">
          <a-button size="small" type="primary" @click="handleDetailSelect">
            <a-icon type="plus"/>
            修改数量
          </a-button>
          <!--<a-button class="margin-left8" size="small" type="danger" @click="handleDel">
            <a-icon type="delete"/>
            删除
          </a-button>-->
        </div>
        <a-table
          ref="table"
          bordered
          :data-source="data"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :row-selection="rowSelection">

        </a-table>
      </a-tab-pane>
    </a-tabs>
    <baseForm ref="baseModal" @ok="handleOk"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="handleCancel">确定</a-button>
    </template>
    <store-select-modal ref="storeSelectModal" @selected="handleStoreSelected"/>
    <purchase-order-select-modal ref="purchaseOrderSelectModal" @selected="handlePurchaseOrderSelected"/>
    <purchase-dispatch-order-select-modal ref="purchaseDispatchOrderSelectModal" @selected="handlePurchaseDispatchOrderSelected"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addInStoreForm, updateInStoreForm } from '@/api/sb/sbcheckform'
import BaseForm from '../../sbcheckdetail/modules/BaseForm'
import PurchaseOrderSelectModal from '@/views/purchase/purchase-order/modules/PurchaseOrderSelectModal'
import PurchaseDispatchOrderSelectModal from '@/views/purchase/purchase-dispatch-order/modules/PurchaseDispatchOrderSelectModal'
import { getInStoreDetailPage, deleteInStoreDetails, fetchInStoreDetail, exportInStoreDetail } from '@/api/sb/sbcheckdetail'

import StoreSelectModal from '@/views/store/store/modules/StoreSelectModal'


export default {
  name: 'BaseInStoreForm',
  components: {
    BaseForm,
    StoreSelectModal,
    PurchaseOrderSelectModal,
    PurchaseDispatchOrderSelectModal
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      storeId: null,
      typeMap: {},
      goodTypeMap: {},
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '物品编号',
          dataIndex: 'no'
        },
        {
          title: '物品名称',
          dataIndex: 'name'
        },
        {
          title: '采购数量',
          dataIndex: 'purchaseNum'
        },
        {
          title: '采购单价',
          dataIndex: 'purchasePrice',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '采购总价',
          dataIndex: 'purchaseTotalPrice',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '数量',
          dataIndex: 'num'
        },
        {
          title: '单价',
          dataIndex: 'price',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        },
        {
          title: '总价',
          dataIndex: 'totalPrice',
          customRender: (text, record, index) => {
            return this.BaseTool.Amount.formatter(text)
          }
        }
      ],
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      }
    }
  },
  props: {
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_CHECK_FORM_TYPE)
    this.goodTypeMap= this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.PURCHASE_APPLY_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_CHECK_FORM_STATUS)
  },
  methods: {
    base (record) {
      this.visible = true
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        return
      }
      this.modalTitle = '编辑'
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'no',
          'storeId',
          'storeName',
          'checkUserId',
          'purchaseId',
          //'purchaseNo',
          'purchaseDispatchOrderId',
          'type',
          'goodType',
          'remark'
        ])))
      })
      this.data = record.detailList
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (this.data.length === 0) {
          this.$message.error('请添加详情')
          this.confirmLoading = false
          return
        }
        values.detailList = this.data
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addInStoreForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateInStoreForm(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },
    handleTypeChange(value) {
      this.type = value;
    },
    handleStoreSelect () {
      this.$refs.storeSelectModal.base({},{filter: 0 })
    },
    handleStoreSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.storeId = key
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'storeId': key,
          'storeName': row.name
        }))
      })
    },
    handlePurchaseOrderSelect () {
      this.$refs.purchaseOrderSelectModal.base({},{filter: 0 })
    },
    handlePurchaseOrderSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'purchaseId': key
        }))
      })
    },
    handlePurchaseDispatchOrderSelect () {
      this.$refs.purchaseDispatchOrderSelectModal.base({},{filter: 0 })
    },
    handlePurchaseDispatchOrderSelected (record, keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'purchaseDispatchOrderId': key
        }))
      })
    },
    handleDetailSelect () {
     if (this.selectedRowKeys.length === 0) {
       this.$message.error('请至少选择一条数据')
       return
     }
     fetchInStoreDetail({ id: this.selectedRowKeys[0] }).then(res => {
       const modal = this.$refs.baseModal
       modal.base(res.data)
     })
     // this.$refs.baseForm.base({id:this.selectedRowKeys[0]})
    },
    handleOk (record) {
      //const { data } = this
      //data.push(record)
      console.log(record)
      this.data = this.data.filter(item => record.id != item.id)
      this.data.push(record)
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    }

  }
}
</script>
